file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity 0.4.17;
import './SafeMath.sol';
import './Pausable.sol';
import './NovaTokenInterface.sol';
/**
* @title Tokensale
* Tokensale allows investors to make token purchases and assigns them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive.
*/
contract TokenSale is Pausable {
using SafeMath for uint256;
NovaTokenInterface public novaToken;
uint256 public totalWeiRaised;
uint256 public tokensMinted;
uint256 public totalSupply;
uint256 public contributors;
uint256 public decimalsMultiplier;
uint256 public startTime;
uint256 public endTime;
uint256 public remainingTokens;
uint256 public allocatedTokens;
bool public finalized;
bool public novaTokensAllocated;
address public novaMultiSig = 0xE1e8fBf326eEed5ddAc1C4a5f757F218E69C86F3;
uint256 public constant BASE_PRICE_IN_WEI = 88000000000000000;
uint256 public constant PUBLIC_TOKENS = 1181031 * (10 ** 18);
uint256 public constant TOTAL_PRESALE_TOKENS = 112386712924725508802400;
uint256 public constant TOKENS_ALLOCATED_TO_PROOF = 1181031 * (10 ** 18);
uint256 public tokenCap = PUBLIC_TOKENS - TOTAL_PRESALE_TOKENS;
uint256 public cap = tokenCap / (10 ** 18);
uint256 public weiCap = cap * BASE_PRICE_IN_WEI;
uint256 public firstDiscountPrice = (BASE_PRICE_IN_WEI * 85) / 100;
uint256 public secondDiscountPrice = (BASE_PRICE_IN_WEI * 90) / 100;
uint256 public thirdDiscountPrice = (BASE_PRICE_IN_WEI * 95) / 100;
uint256 public firstDiscountCap = (weiCap * 5) / 100;
uint256 public secondDiscountCap = (weiCap * 10) / 100;
uint256 public thirdDiscountCap = (weiCap * 20) / 100;
bool public started = false;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event NewClonedToken(address indexed _cloneToken);
event OnTransfer(address _from, address _to, uint _amount);
event OnApprove(address _owner, address _spender, uint _amount);
event LogInt(string _name, uint256 _value);
event Finalized();
function TokenSale(address _tokenAddress, uint256 _startTime, uint256 _endTime) public {
require(_tokenAddress != 0x0);
require(_startTime > 0);
require(_endTime > _startTime);
startTime = _startTime;
endTime = _endTime;
novaToken = NovaTokenInterface(_tokenAddress);
decimalsMultiplier = (10 ** 18);
}
/**
* High level token purchase function
*/
function() public payable {
buyTokens(msg.sender);
}
/**
* Low level token purchase function
* @param _beneficiary will receive the tokens.
*/
function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized {
require(_beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 priceInWei = getPriceInWei();
totalWeiRaised = totalWeiRaised.add(weiAmount);
uint256 tokens = weiAmount.mul(decimalsMultiplier).div(priceInWei);
tokensMinted = tokensMinted.add(tokens);
require(tokensMinted < tokenCap);
contributors = contributors.add(1);
novaToken.mint(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
forwardFunds();
}
/**
* Get the price in wei for current premium
* @return price {uint256}
*/
function getPriceInWei() constant public returns (uint256) {
uint256 price;
if (totalWeiRaised < firstDiscountCap) {
price = firstDiscountPrice;
} else if (totalWeiRaised < secondDiscountCap) {
price = secondDiscountPrice;
} else if (totalWeiRaised < thirdDiscountCap) {
price = thirdDiscountPrice;
} else {
price = BASE_PRICE_IN_WEI;
}
return price;
}
/**
* Forwards funds to the tokensale wallet
*/
function forwardFunds() internal {
novaMultiSig.transfer(msg.value);
}
/**
* Validates the purchase (period, minimum amount, within cap)
* @return {bool} valid
*/
function validPurchase() internal constant returns (bool) {
uint256 current = now;
bool presaleStarted = (current >= startTime || started);
bool presaleNotEnded = current <= endTime;
bool nonZeroPurchase = msg.value != 0;
return nonZeroPurchase && presaleStarted && presaleNotEnded;
}
/**
* Returns the total Nova token supply
* @return totalSupply {uint256} Nova Token Total Supply
*/
function totalSupply() public constant returns (uint256) {
return novaToken.totalSupply();
}
/**
* Returns token holder Nova Token balance
* @param _owner {address} Token holder address
* @return balance {uint256} Corresponding token holder balance
*/
function balanceOf(address _owner) public constant returns (uint256) {
return novaToken.balanceOf(_owner);
}
/**
* Change the Nova Token controller
* @param _newController {address} New Nova Token controller
*/
function changeController(address _newController) public {
require(isContract(_newController));
novaToken.transferControl(_newController);
}
function enableTransfers() public {
if (now < endTime) {
require(msg.sender == owner);
}
novaToken.enableTransfers(true);
}
function lockTransfers() public onlyOwner {
require(now < endTime);
novaToken.enableTransfers(false);
}
function enableMasterTransfers() public onlyOwner {
novaToken.enableMasterTransfers(true);
}
function lockMasterTransfers() public onlyOwner {
novaToken.enableMasterTransfers(false);
}
function forceStart() public onlyOwner {
started = true;
}
function allocateNovaTokens() public onlyOwner whenNotFinalized {
require(!novaTokensAllocated);
novaToken.mint(novaMultiSig, TOKENS_ALLOCATED_TO_PROOF);
novaTokensAllocated = true;
}
function finalize() public onlyOwner {
require(paused);
require(novaTokensAllocated);
novaToken.finishMinting();
novaToken.enableTransfers(true);
Finalized();
finalized = true;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
modifier whenNotFinalized() {
require(!finalized);
_;
}
} | Get the price in wei for current premium return price {uint256}/ | function getPriceInWei() constant public returns (uint256) {
uint256 price;
if (totalWeiRaised < firstDiscountCap) {
price = firstDiscountPrice;
price = secondDiscountPrice;
price = thirdDiscountPrice;
price = BASE_PRICE_IN_WEI;
}
return price;
}
| 1,844,466 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ConfigurableOperational
* @notice A configurable with modifiers for operational mode state validation
*/
contract ConfigurableOperational is Configurable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyOperationalModeNormal() {
require(configuration.isOperationalModeNormal(), "Operational mode is not normal [ConfigurableOperational.sol:22]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentTypesLib
* @dev Data types centered around payment
*/
library PaymentTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum PaymentPartyRole {Sender, Recipient}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct PaymentSenderParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
string data;
}
struct PaymentRecipientParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.TotalOriginFigures fees;
}
struct Operator {
uint256 id;
string data;
}
struct Payment {
int256 amount;
MonetaryTypesLib.Currency currency;
PaymentSenderParty sender;
PaymentRecipientParty recipient;
// Positive transfer is always in direction from sender to recipient
NahmiiTypesLib.SingleTotalInt256 transfers;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
Operator operator;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function PAYMENT_KIND()
public
pure
returns (string memory)
{
return "payment";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHasher
* @notice Contract that hashes types related to payment
*/
contract PaymentHasher is Ownable {
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function hashPaymentAsWallet(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 amountCurrencyHash = hashPaymentAmountCurrency(payment);
bytes32 senderHash = hashPaymentSenderPartyAsWallet(payment.sender);
bytes32 recipientHash = hashAddress(payment.recipient.wallet);
return keccak256(abi.encodePacked(amountCurrencyHash, senderHash, recipientHash));
}
function hashPaymentAsOperator(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 walletSignatureHash = hashSignature(payment.seals.wallet.signature);
bytes32 senderHash = hashPaymentSenderPartyAsOperator(payment.sender);
bytes32 recipientHash = hashPaymentRecipientPartyAsOperator(payment.recipient);
bytes32 transfersHash = hashSingleTotalInt256(payment.transfers);
bytes32 operatorHash = hashString(payment.operator.data);
return keccak256(abi.encodePacked(
walletSignatureHash, senderHash, recipientHash, transfersHash, operatorHash
));
}
function hashPaymentAmountCurrency(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
payment.amount,
payment.currency.ct,
payment.currency.id
));
}
function hashPaymentSenderPartyAsWallet(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
paymentSenderParty.wallet,
paymentSenderParty.data
));
}
function hashPaymentSenderPartyAsOperator(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentSenderParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentSenderParty.balances);
bytes32 singleFeeHash = hashFigure(paymentSenderParty.fees.single);
bytes32 totalFeesHash = hashOriginFigures(paymentSenderParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, singleFeeHash, totalFeesHash
));
}
function hashPaymentRecipientPartyAsOperator(
PaymentTypesLib.PaymentRecipientParty memory paymentRecipientParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentRecipientParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentRecipientParty.balances);
bytes32 totalFeesHash = hashOriginFigures(paymentRecipientParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, totalFeesHash
));
}
function hashCurrentPreviousInt256(
NahmiiTypesLib.CurrentPreviousInt256 memory currentPreviousInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
currentPreviousInt256.current,
currentPreviousInt256.previous
));
}
function hashSingleTotalInt256(
NahmiiTypesLib.SingleTotalInt256 memory singleTotalInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
singleTotalInt256.single,
singleTotalInt256.total
));
}
function hashFigure(MonetaryTypesLib.Figure memory figure)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
figure.amount,
figure.currency.ct,
figure.currency.id
));
}
function hashOriginFigures(NahmiiTypesLib.OriginFigure[] memory originFigures)
public
pure
returns (bytes32)
{
bytes32 hash;
for (uint256 i = 0; i < originFigures.length; i++) {
hash = keccak256(abi.encodePacked(
hash,
originFigures[i].originId,
originFigures[i].figure.amount,
originFigures[i].figure.currency.ct,
originFigures[i].figure.currency.id
)
);
}
return hash;
}
function hashUint256(uint256 _uint256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_uint256));
}
function hashString(string memory _string)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
function hashAddress(address _address)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_address));
}
function hashSignature(NahmiiTypesLib.Signature memory signature)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
signature.v,
signature.r,
signature.s
));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHashable
* @notice An ownable that has a payment hasher property
*/
contract PaymentHashable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
PaymentHasher public paymentHasher;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetPaymentHasherEvent(PaymentHasher oldPaymentHasher, PaymentHasher newPaymentHasher);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the payment hasher contract
/// @param newPaymentHasher The (address of) PaymentHasher contract instance
function setPaymentHasher(PaymentHasher newPaymentHasher)
public
onlyDeployer
notNullAddress(address(newPaymentHasher))
notSameAddresses(address(newPaymentHasher), address(paymentHasher))
{
// Set new payment hasher
PaymentHasher oldPaymentHasher = paymentHasher;
paymentHasher = newPaymentHasher;
// Emit event
emit SetPaymentHasherEvent(oldPaymentHasher, newPaymentHasher);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier paymentHasherInitialized() {
require(address(paymentHasher) != address(0), "Payment hasher not initialized [PaymentHashable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManager
* @notice A contract to control who can execute some specific actions
*/
contract SignerManager is Ownable {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => uint256) public signerIndicesMap; // 1 based internally
address[] public signers;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterSignerEvent(address signer);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
registerSigner(deployer);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Gauge whether an address is registered signer
/// @param _address The concerned address
/// @return true if address is registered signer, else false
function isSigner(address _address)
public
view
returns (bool)
{
return 0 < signerIndicesMap[_address];
}
/// @notice Get the count of registered signers
/// @return The count of registered signers
function signersCount()
public
view
returns (uint256)
{
return signers.length;
}
/// @notice Get the 0 based index of the given address in the list of signers
/// @param _address The concerned address
/// @return The index of the signer address
function signerIndex(address _address)
public
view
returns (uint256)
{
require(isSigner(_address), "Address not signer [SignerManager.sol:71]");
return signerIndicesMap[_address] - 1;
}
/// @notice Registers a signer
/// @param newSigner The address of the signer to register
function registerSigner(address newSigner)
public
onlyOperator
notNullOrThisAddress(newSigner)
{
if (0 == signerIndicesMap[newSigner]) {
// Set new operator
signers.push(newSigner);
signerIndicesMap[newSigner] = signers.length;
// Emit event
emit RegisterSignerEvent(newSigner);
}
}
/// @notice Get the subset of registered signers in the given 0 based index range
/// @param low The lower inclusive index
/// @param up The upper inclusive index
/// @return The subset of registered signers
function signersByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < signers.length, "No signers found [SignerManager.sol:101]");
require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]");
up = up.clampMax(signers.length - 1);
address[] memory _signers = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_signers[i - low] = signers[i];
return _signers;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManageable
* @notice A contract to interface ACL
*/
contract SignerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SignerManager public signerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the signer manager of this contract
/// @param newSignerManager The address of the new signer
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
//set new signer
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
// Emit event
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
/// @notice Prefix input hash and do ecrecover on prefixed hash
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return The address recovered
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
/// @notice Gauge whether a signature of a hash has been signed by a registered signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return true if the recovered signer is one of the registered signers, else false
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
/// @notice Gauge whether a signature of a hash has been signed by the claimed signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @param signer The claimed signer
/// @return true if the recovered signer equals the input signer, else false
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validator
* @notice An ownable that validates valuable types (e.g. payment)
*/
contract Validator is Ownable, SignerManageable, Configurable, PaymentHashable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer, address signerManager) Ownable(deployer) SignerManageable(signerManager) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isGenuineOperatorSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature)
public
view
returns (bool)
{
return isSignedByRegisteredSigner(hash, signature.v, signature.r, signature.s);
}
function isGenuineWalletSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature, address wallet)
public
pure
returns (bool)
{
return isSignedBy(hash, signature.v, signature.r, signature.s, wallet);
}
function isGenuinePaymentWalletHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsWallet(payment) == payment.seals.wallet.hash;
}
function isGenuinePaymentOperatorHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsOperator(payment) == payment.seals.operator.hash;
}
function isGenuinePaymentWalletSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletHash(payment)
&& isGenuineWalletSignature(payment.seals.wallet.hash, payment.seals.wallet.signature, payment.sender.wallet);
}
function isGenuinePaymentOperatorSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentOperatorHash(payment)
&& isGenuineOperatorSignature(payment.seals.operator.hash, payment.seals.operator.signature);
}
function isGenuinePaymentSeals(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletSeal(payment) && isGenuinePaymentOperatorSeal(payment);
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentFeeOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
int256 feePartsPer = int256(ConstantsLib.PARTS_PER());
int256 feeAmount = payment.amount
.mul(
configuration.currencyPaymentFee(
payment.blockNumber, payment.currency.ct, payment.currency.id, payment.amount
)
).div(feePartsPer);
if (1 > feeAmount)
feeAmount = 1;
return (payment.sender.fees.single.amount == feeAmount);
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentFeeOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
(address feeCurrencyCt, uint256 feeCurrencyId) = configuration.feeCurrency(
payment.blockNumber, payment.currency.ct, payment.currency.id
);
return feeCurrencyCt == payment.sender.fees.single.currency.ct
&& feeCurrencyId == payment.sender.fees.single.currency.id;
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentSenderOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet))
&& (payment.sender.balances.current == payment.sender.balances.previous.sub(payment.transfers.single).sub(payment.sender.fees.single.amount));
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentRecipientOfFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (payment.recipient.balances.current == payment.recipient.balances.previous.add(payment.transfers.single));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentSenderOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentRecipientOfNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet);
}
function isSuccessivePaymentsPartyNonces(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole
)
public
pure
returns (bool)
{
uint256 firstNonce = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.nonce : firstPayment.recipient.nonce);
uint256 lastNonce = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.nonce : lastPayment.recipient.nonce);
return lastNonce == firstNonce.add(1);
}
function isGenuineSuccessivePaymentsBalances(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole,
int256 delta
)
public
pure
returns (bool)
{
NahmiiTypesLib.CurrentPreviousInt256 memory firstCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.balances : firstPayment.recipient.balances);
NahmiiTypesLib.CurrentPreviousInt256 memory lastCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.balances : lastPayment.recipient.balances);
return lastCurrentPreviousBalances.previous == firstCurrentPreviousBalances.current.add(delta);
}
function isGenuineSuccessivePaymentsTotalFees(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.Payment memory lastPayment
)
public
pure
returns (bool)
{
MonetaryTypesLib.Figure memory firstTotalFee = getProtocolFigureByCurrency(firstPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
MonetaryTypesLib.Figure memory lastTotalFee = getProtocolFigureByCurrency(lastPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
return lastTotalFee.amount == firstTotalFee.amount.add(lastPayment.sender.fees.single.amount);
}
function isPaymentParty(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet || wallet == payment.recipient.wallet;
}
function isPaymentSender(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet;
}
function isPaymentRecipient(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.recipient.wallet;
}
function isPaymentCurrency(PaymentTypesLib.Payment memory payment, MonetaryTypesLib.Currency memory currency)
public
pure
returns (bool)
{
return currency.ct == payment.currency.ct && currency.id == payment.currency.id;
}
function isPaymentCurrencyNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return payment.currency.ct != payment.sender.fees.single.currency.ct
|| payment.currency.id != payment.sender.fees.single.currency.id;
}
//
// Private unctions
// -----------------------------------------------------------------------------------------------------------------
function getProtocolFigureByCurrency(NahmiiTypesLib.OriginFigure[] memory originFigures, MonetaryTypesLib.Currency memory currency)
private
pure
returns (MonetaryTypesLib.Figure memory) {
for (uint256 i = 0; i < originFigures.length; i++)
if (originFigures[i].figure.currency.ct == currency.ct && originFigures[i].figure.currency.id == currency.id
&& originFigures[i].originId == 0)
return originFigures[i].figure;
return MonetaryTypesLib.Figure(0, currency);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TradeTypesLib
* @dev Data types centered around trade
*/
library TradeTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum CurrencyRole {Intended, Conjugate}
enum LiquidityRole {Maker, Taker}
enum Intention {Buy, Sell}
enum TradePartyRole {Buyer, Seller}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OrderPlacement {
Intention intention;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct Order {
uint256 nonce;
address wallet;
OrderPlacement placement;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
uint256 operatorId;
}
struct TradeOrder {
int256 amount;
NahmiiTypesLib.WalletOperatorHashes hashes;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct TradeParty {
uint256 nonce;
address wallet;
uint256 rollingVolume;
LiquidityRole liquidityRole;
TradeOrder order;
NahmiiTypesLib.IntendedConjugateCurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
}
struct Trade {
uint256 nonce;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
TradeParty buyer;
TradeParty seller;
// Positive intended transfer is always in direction from seller to buyer
// Positive conjugate transfer is always in direction from buyer to seller
NahmiiTypesLib.IntendedConjugateSingleTotalInt256 transfers;
NahmiiTypesLib.Seal seal;
uint256 blockNumber;
uint256 operatorId;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function TRADE_KIND()
public
pure
returns (string memory)
{
return "trade";
}
function ORDER_KIND()
public
pure
returns (string memory)
{
return "order";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validatable
* @notice An ownable that has a validator property
*/
contract Validatable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Validator public validator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetValidatorEvent(Validator oldValidator, Validator newValidator);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the validator contract
/// @param newValidator The (address of) Validator contract instance
function setValidator(Validator newValidator)
public
onlyDeployer
notNullAddress(address(newValidator))
notSameAddresses(address(newValidator), address(validator))
{
//set new validator
Validator oldValidator = validator;
validator = newValidator;
// Emit event
emit SetValidatorEvent(oldValidator, newValidator);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier validatorInitialized() {
require(address(validator) != address(0), "Validator not initialized [Validatable.sol:55]");
_;
}
modifier onlyOperatorSealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentOperatorSeal(payment), "Payment operator seal not genuine [Validatable.sol:60]");
_;
}
modifier onlySealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentSeals(payment), "Payment seals not genuine [Validatable.sol:65]");
_;
}
modifier onlyPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentParty(payment, wallet), "Wallet not payment party [Validatable.sol:70]");
_;
}
modifier onlyPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentSender(payment, wallet), "Wallet not payment sender [Validatable.sol:75]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBond
* @notice Fund that contains crypto incentive for challenging operator fraud.
*/
contract SecurityBond is Ownable, Configurable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public REWARD_ACTION = "reward";
string constant public DEPRIVE_ACTION = "deprive";
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct FractionalReward {
uint256 fraction;
uint256 nonce;
uint256 unlockTime;
}
struct AbsoluteReward {
int256 amount;
uint256 nonce;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance private deposited;
TxHistoryLib.TxHistory private txHistory;
CurrenciesLib.Currencies private inUseCurrencies;
mapping(address => FractionalReward) public fractionalRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => AbsoluteReward))) public absoluteRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => uint256))) public claimNonceByWalletCurrency;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
mapping(address => uint256) public nonceByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RewardFractionalEvent(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds);
event RewardAbsoluteEvent(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds);
event DepriveFractionalEvent(address wallet);
event DepriveAbsoluteEvent(address wallet, address currencyCt, uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address from, Beneficiary beneficiary, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Servable() public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balance
deposited.add(amount, address(0), 0);
txHistory.addDeposit(amount, address(0), 0);
// Add currency to in-use list
inUseCurrencies.add(address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:145]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [SecurityBond.sol:154]");
// Add to balance
deposited.add(amount, currencyCt, currencyId);
txHistory.addDeposit(amount, currencyCt, currencyId);
// Add currency to in-use list
inUseCurrencies.add(currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the deposited balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function depositedBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId);
}
/// @notice Get the fractional amount deposited balance of the given currency
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
/// @param fraction The fraction of sums that the wallet is rewarded
/// @return The fractional amount of deposited balance
function depositedFractionalBalance(address currencyCt, uint256 currencyId, uint256 fraction)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fraction))
.div(ConstantsLib.PARTS_PER());
}
/// @notice Get the staged balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded
/// @return The number of currencies
function inUseCurrenciesCount()
public
view
returns (uint256)
{
return inUseCurrencies.count();
}
/// @notice Get the currencies recorded with indices in the given range
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range
function inUseCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return inUseCurrencies.getByIndices(low, up);
}
/// @notice Reward the given wallet the given fraction of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param fraction The fraction of sums that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardFractional(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = fraction.clampMax(uint256(ConstantsLib.PARTS_PER()));
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardFractionalEvent(wallet, fraction, unlockTimeoutInSeconds);
}
/// @notice Reward the given wallet the given amount of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param amount The amount that the wallet is rewarded
/// @param currencyCt The contract address of the currency that the wallet is rewarded
/// @param currencyId The ID of the currency that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardAbsolute(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = amount;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardAbsoluteEvent(wallet, amount, currencyCt, currencyId, unlockTimeoutInSeconds);
}
/// @notice Deprive the given wallet of any fractional reward it has been granted
/// @param wallet The concerned wallet
function depriveFractional(address wallet)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = 0;
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = 0;
// Emit event
emit DepriveFractionalEvent(wallet);
}
/// @notice Deprive the given wallet of any absolute reward it has been granted in the given currency
/// @param wallet The concerned wallet
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
function depriveAbsolute(address wallet, address currencyCt, uint256 currencyId)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = 0;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = 0;
// Emit event
emit DepriveAbsoluteEvent(wallet, currencyCt, currencyId);
}
/// @notice Claim reward and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(msg.sender, balanceType);
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [SecurityBond.sol:350]");
beneficiary.receiveTokensTo(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, beneficiary, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim reward and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Add to staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:386]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [SecurityBond.sol:405]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Combine claim nonce from rewards
uint256 claimNonce = fractionalRewardByWallet[wallet].nonce.clampMin(
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce
);
// Require that new claim nonce is strictly greater than current stored one
require(
claimNonce > claimNonceByWalletCurrency[wallet][currencyCt][currencyId],
"Claim nonce not strictly greater than previously claimed nonce [SecurityBond.sol:425]"
);
// Combine claim amount from rewards
int256 claimAmount = _fractionalRewardAmountByWalletCurrency(wallet, currencyCt, currencyId).add(
_absoluteRewardAmountByWalletCurrency(wallet, currencyCt, currencyId)
).clampMax(
deposited.get(currencyCt, currencyId)
);
// Require that claim amount is strictly positive, indicating that there is an amount to claim
require(claimAmount.isNonZeroPositiveInt256(), "Claim amount not strictly positive [SecurityBond.sol:438]");
// Update stored claim nonce for wallet and currency
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] = claimNonce;
return claimAmount;
}
function _fractionalRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < fractionalRewardByWallet[wallet].nonce &&
block.timestamp >= fractionalRewardByWallet[wallet].unlockTime
)
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fractionalRewardByWallet[wallet].fraction))
.div(ConstantsLib.PARTS_PER());
else
return 0;
}
function _absoluteRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce &&
block.timestamp >= absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime
)
return absoluteRewardByWallet[wallet][currencyCt][currencyId].amount.clampMax(
deposited.get(currencyCt, currencyId)
);
else
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBondable
* @notice An ownable that has a security bond property
*/
contract SecurityBondable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SecurityBond public securityBond;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSecurityBondEvent(SecurityBond oldSecurityBond, SecurityBond newSecurityBond);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the security bond contract
/// @param newSecurityBond The (address of) SecurityBond contract instance
function setSecurityBond(SecurityBond newSecurityBond)
public
onlyDeployer
notNullAddress(address(newSecurityBond))
notSameAddresses(address(newSecurityBond), address(securityBond))
{
//set new security bond
SecurityBond oldSecurityBond = securityBond;
securityBond = newSecurityBond;
// Emit event
emit SetSecurityBondEvent(oldSecurityBond, newSecurityBond);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier securityBondInitialized() {
require(address(securityBond) != address(0), "Security bond not initialized [SecurityBondable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallenge
* @notice Where fraud challenge results are found
*/
contract FraudChallenge is Ownable, Servable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public ADD_SEIZED_WALLET_ACTION = "add_seized_wallet";
string constant public ADD_DOUBLE_SPENDER_WALLET_ACTION = "add_double_spender_wallet";
string constant public ADD_FRAUDULENT_ORDER_ACTION = "add_fraudulent_order";
string constant public ADD_FRAUDULENT_TRADE_ACTION = "add_fraudulent_trade";
string constant public ADD_FRAUDULENT_PAYMENT_ACTION = "add_fraudulent_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address[] public doubleSpenderWallets;
mapping(address => bool) public doubleSpenderByWallet;
bytes32[] public fraudulentOrderHashes;
mapping(bytes32 => bool) public fraudulentByOrderHash;
bytes32[] public fraudulentTradeHashes;
mapping(bytes32 => bool) public fraudulentByTradeHash;
bytes32[] public fraudulentPaymentHashes;
mapping(bytes32 => bool) public fraudulentByPaymentHash;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AddDoubleSpenderWalletEvent(address wallet);
event AddFraudulentOrderHashEvent(bytes32 hash);
event AddFraudulentTradeHashEvent(bytes32 hash);
event AddFraudulentPaymentHashEvent(bytes32 hash);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the number of wallets tagged as double spenders
/// @return Number of double spender wallets
function doubleSpenderWalletsCount()
public
view
returns (uint256)
{
return doubleSpenderWallets.length;
}
/// @notice Add given wallets to store of double spender wallets if not already present
/// @param wallet The first wallet to add
function addDoubleSpenderWallet(address wallet)
public
onlyEnabledServiceAction(ADD_DOUBLE_SPENDER_WALLET_ACTION) {
if (!doubleSpenderByWallet[wallet]) {
doubleSpenderWallets.push(wallet);
doubleSpenderByWallet[wallet] = true;
emit AddDoubleSpenderWalletEvent(wallet);
}
}
/// @notice Get the number of fraudulent order hashes
function fraudulentOrderHashesCount()
public
view
returns (uint256)
{
return fraudulentOrderHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent order
/// @param hash The hash to be tested
function isFraudulentOrderHash(bytes32 hash)
public
view returns (bool) {
return fraudulentByOrderHash[hash];
}
/// @notice Add given order hash to store of fraudulent order hashes if not already present
function addFraudulentOrderHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_ORDER_ACTION)
{
if (!fraudulentByOrderHash[hash]) {
fraudulentByOrderHash[hash] = true;
fraudulentOrderHashes.push(hash);
emit AddFraudulentOrderHashEvent(hash);
}
}
/// @notice Get the number of fraudulent trade hashes
function fraudulentTradeHashesCount()
public
view
returns (uint256)
{
return fraudulentTradeHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent trade
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent trade, else false
function isFraudulentTradeHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByTradeHash[hash];
}
/// @notice Add given trade hash to store of fraudulent trade hashes if not already present
function addFraudulentTradeHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_TRADE_ACTION)
{
if (!fraudulentByTradeHash[hash]) {
fraudulentByTradeHash[hash] = true;
fraudulentTradeHashes.push(hash);
emit AddFraudulentTradeHashEvent(hash);
}
}
/// @notice Get the number of fraudulent payment hashes
function fraudulentPaymentHashesCount()
public
view
returns (uint256)
{
return fraudulentPaymentHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent payment
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent payment, else null
function isFraudulentPaymentHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByPaymentHash[hash];
}
/// @notice Add given payment hash to store of fraudulent payment hashes if not already present
function addFraudulentPaymentHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_PAYMENT_ACTION)
{
if (!fraudulentByPaymentHash[hash]) {
fraudulentByPaymentHash[hash] = true;
fraudulentPaymentHashes.push(hash);
emit AddFraudulentPaymentHashEvent(hash);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallengable
* @notice An ownable that has a fraud challenge property
*/
contract FraudChallengable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FraudChallenge public fraudChallenge;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetFraudChallengeEvent(FraudChallenge oldFraudChallenge, FraudChallenge newFraudChallenge);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the fraud challenge contract
/// @param newFraudChallenge The (address of) FraudChallenge contract instance
function setFraudChallenge(FraudChallenge newFraudChallenge)
public
onlyDeployer
notNullAddress(address(newFraudChallenge))
notSameAddresses(address(newFraudChallenge), address(fraudChallenge))
{
// Set new fraud challenge
FraudChallenge oldFraudChallenge = fraudChallenge;
fraudChallenge = newFraudChallenge;
// Emit event
emit SetFraudChallengeEvent(oldFraudChallenge, newFraudChallenge);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier fraudChallengeInitialized() {
require(address(fraudChallenge) != address(0), "Fraud challenge not initialized [FraudChallengable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BalanceTrackerLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
function fungibleActiveRecordByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 _blockNumber)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.depositedBalanceType(), currency.ct, currency.id, _blockNumber
);
(int256 settledAmount, uint256 settledBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.settledBalanceType(), currency.ct, currency.id, _blockNumber
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
function fungibleActiveBalanceAmountByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = fungibleActiveRecordByBlockNumber(self, wallet, currency, blockNumber);
return amount;
}
function fungibleActiveDeltaBalanceAmountByBlockNumbers(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 fromBlockNumber, uint256 toBlockNumber)
internal
view
returns (int256)
{
return fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, toBlockNumber) -
fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, fromBlockNumber);
}
// TODO Rename?
function fungibleActiveRecord(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.lastFungibleRecord(
wallet, self.depositedBalanceType(), currency.ct, currency.id
);
(int256 settledAmount, uint256 settledBlockNumber) = self.lastFungibleRecord(
wallet, self.settledBalanceType(), currency.ct, currency.id
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
// TODO Rename?
function fungibleActiveBalanceAmount(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256)
{
return self.get(wallet, self.depositedBalanceType(), currency.ct, currency.id).add(
self.get(wallet, self.settledBalanceType(), currency.ct, currency.id)
);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementDisputeByPayment
* @notice The where payment related disputes of null settlement challenge happens
*/
contract NullSettlementDisputeByPayment is Ownable, Configurable, Validatable, SecurityBondable, WalletLockable,
BalanceTrackable, FraudChallengable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CHALLENGE_BY_PAYMENT_ACTION = "challenge_by_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event ChallengeByPaymentEvent(address wallet, uint256 nonce, PaymentTypesLib.Payment payment,
address challenger);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
/// @notice Set the settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Challenge the settlement by providing payment candidate
/// @dev This challenges the payment sender's side of things
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges
/// @param challenger The address of the challenger
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment, address challenger)
public
onlyEnabledServiceAction(CHALLENGE_BY_PAYMENT_ACTION)
onlySealedPayment(payment)
onlyPaymentSender(payment, wallet)
{
// Require that payment candidate is not labelled fraudulent
require(!fraudChallenge.isFraudulentPaymentHash(payment.seals.operator.hash), "Payment deemed fraudulent [NullSettlementDisputeByPayment.sol:86]");
// Require that proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, payment.currency), "No proposal found [NullSettlementDisputeByPayment.sol:89]");
// Require that proposal has not expired
require(!nullSettlementChallengeState.hasProposalExpired(wallet, payment.currency), "Proposal found expired [NullSettlementDisputeByPayment.sol:92]");
// Require that payment party's nonce is strictly greater than proposal's nonce and its current
// disqualification nonce
require(payment.sender.nonce > nullSettlementChallengeState.proposalNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal nonce [NullSettlementDisputeByPayment.sol:96]");
require(payment.sender.nonce > nullSettlementChallengeState.proposalDisqualificationNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal disqualification nonce [NullSettlementDisputeByPayment.sol:99]");
// Require overrun for this payment to be a valid challenge candidate
require(_overrun(wallet, payment), "No overrun found [NullSettlementDisputeByPayment.sol:104]");
// Reward challenger
_settleRewards(wallet, payment.sender.balances.current, payment.currency, challenger);
// Disqualify proposal, effectively overriding any previous disqualification
nullSettlementChallengeState.disqualifyProposal(
wallet, payment.currency, challenger, payment.blockNumber,
payment.sender.nonce, payment.seals.operator.hash, PaymentTypesLib.PAYMENT_KIND()
);
// Emit event
emit ChallengeByPaymentEvent(
wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), payment, challenger
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _overrun(address wallet, PaymentTypesLib.Payment memory payment)
private
view
returns (bool)
{
// Get the target balance amount from the proposal
int targetBalanceAmount = nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, payment.currency
);
// Get the change in active balance since the start of the challenge
int256 deltaBalanceSinceStart = balanceTracker.fungibleActiveBalanceAmount(
wallet, payment.currency
).sub(
balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency,
nullSettlementChallengeState.proposalReferenceBlockNumber(wallet, payment.currency)
)
);
// Get the cumulative transfer of the payment
int256 cumulativeTransfer = balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency, payment.blockNumber
).sub(payment.sender.balances.current);
return targetBalanceAmount.add(deltaBalanceSinceStart) < cumulativeTransfer;
}
// Lock wallet's balances or reward challenger by stake fraction
function _settleRewards(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
if (nullSettlementChallengeState.proposalWalletInitiated(wallet, currency))
_settleBalanceReward(wallet, walletAmount, currency, challenger);
else
_settleSecurityBondReward(wallet, walletAmount, currency, challenger);
}
function _settleBalanceReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Unlock wallet/currency for existing challenger if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
walletLocker.unlockFungibleByProxy(
wallet,
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Lock wallet for new challenger
walletLocker.lockFungibleByProxy(
wallet, challenger, walletAmount, currency.ct, currency.id, configuration.settlementChallengeTimeout()
);
}
// Settle the two-component reward from security bond.
// The first component is flat figure as obtained from Configuration
// The second component is progressive and calculated as
// min(walletAmount, fraction of SecurityBond's deposited balance)
// both amounts for the given currency
function _settleSecurityBondReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Deprive existing challenger of reward if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
securityBond.depriveAbsolute(
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Reward the flat component
MonetaryTypesLib.Figure memory flatReward = _flatReward();
securityBond.rewardAbsolute(
challenger, flatReward.amount, flatReward.currency.ct, flatReward.currency.id, 0
);
// Reward the progressive component
int256 progressiveRewardAmount = walletAmount.clampMax(
securityBond.depositedFractionalBalance(
currency.ct, currency.id, configuration.operatorSettlementStakeFraction()
)
);
securityBond.rewardAbsolute(
challenger, progressiveRewardAmount, currency.ct, currency.id, 0
);
}
function _flatReward()
private
view
returns (MonetaryTypesLib.Figure memory)
{
(int256 amount, address currencyCt, uint256 currencyId) = configuration.operatorSettlementStake();
return MonetaryTypesLib.Figure(amount, MonetaryTypesLib.Currency(currencyCt, currencyId));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeByPayment
* @notice Where null settlements pertaining to payments are started and disputed
*/
contract NullSettlementChallengeByPayment is Ownable, ConfigurableOperational, BalanceTrackable, WalletLockable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementDisputeByPayment public nullSettlementDisputeByPayment;
NullSettlementChallengeState public nullSettlementChallengeState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementDisputeByPaymentEvent(NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment,
NullSettlementDisputeByPayment newNullSettlementDisputeByPayment);
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event StartChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId);
event StartChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId, address proxy);
event StopChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId);
event StopChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address proxy);
event ChallengeByPaymentEvent(address challengedWallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address challengerWallet);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the settlement dispute contract
/// @param newNullSettlementDisputeByPayment The (address of) NullSettlementDisputeByPayment contract instance
function setNullSettlementDisputeByPayment(NullSettlementDisputeByPayment newNullSettlementDisputeByPayment)
public
onlyDeployer
notNullAddress(address(newNullSettlementDisputeByPayment))
{
NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment = nullSettlementDisputeByPayment;
nullSettlementDisputeByPayment = newNullSettlementDisputeByPayment;
emit SetNullSettlementDisputeByPaymentEvent(oldNullSettlementDisputeByPayment, nullSettlementDisputeByPayment);
}
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Start settlement challenge
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallenge(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Require that wallet is not locked
require(!walletLocker.isLocked(msg.sender), "Wallet found locked [NullSettlementChallengeByPayment.sol:116]");
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(msg.sender, amount, currency, true);
// Emit event
emit StartChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Start settlement challenge for the given wallet
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(wallet, amount, currency, false);
// Emit event
emit StartChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Stop settlement challenge
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallenge(address currencyCt, uint256 currencyId)
public
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(msg.sender, currency, true);
// Emit event
emit StopChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
nullSettlementChallengeState.proposalStageAmount(msg.sender, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Stop settlement challenge
/// @param wallet The concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallengeByProxy(address wallet, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(wallet, currency, false);
// Emit event
emit StopChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
nullSettlementChallengeState.proposalStageAmount(wallet, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has been defined
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has been initiated, else false
function hasProposal(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposal(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalTerminated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalExpired(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge nonce of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge nonce
function proposalNonce(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalNonce(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal block number of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal block number
function proposalReferenceBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalReferenceBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal end time of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal end time
function proposalExpirationTime(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalExpirationTime(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge status of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge status
function proposalStatus(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (SettlementChallengeTypesLib.Status)
{
return nullSettlementChallengeState.proposalStatus(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalStageAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the balance reward of the given wallet's settlement proposal
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The balance reward of the settlement proposal
function proposalWalletInitiated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.proposalWalletInitiated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenger of the settlement disqualification
function proposalDisqualificationChallenger(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (address)
{
return nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The block number of the settlement disqualification
function proposalDisqualificationBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalDisqualificationBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate kind of the settlement disqualification
function proposalDisqualificationCandidateKind(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (string memory)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateKind(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate hash of the settlement disqualification
function proposalDisqualificationCandidateHash(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bytes32)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateHash(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Challenge the settlement by providing payment candidate
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges the null
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment)
public
onlyOperationalModeNormal
{
// Challenge by payment
nullSettlementDisputeByPayment.challengeByPayment(wallet, payment, msg.sender);
// Emit event
emit ChallengeByPaymentEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, payment.currency),
nullSettlementChallengeState.proposalStageAmount(wallet, payment.currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, payment.currency),
payment.currency.ct, payment.currency.id, msg.sender
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _startChallenge(address wallet, int256 stageAmount, MonetaryTypesLib.Currency memory currency,
bool walletInitiated)
private
{
// Require that current block number is beyond the earliest settlement challenge block number
require(
block.number >= configuration.earliestSettlementBlockNumber(),
"Current block number below earliest settlement block number [NullSettlementChallengeByPayment.sol:443]"
);
// Require that there is no ongoing overlapping null settlement challenge
require(
!nullSettlementChallengeState.hasProposal(wallet, currency) ||
nullSettlementChallengeState.hasProposalExpired(wallet, currency),
"Overlapping null settlement challenge proposal found [NullSettlementChallengeByPayment.sol:449]"
);
// Get the last logged active balance amount and block number, properties of overlapping DSC
// and the baseline nonce
(
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) = _externalProperties(
wallet, currency
);
// Initiate proposal, including assurance that there is no overlap with active proposal
// Target balance amount is calculated as current balance - DSC cumulativeTransferAmount - DSC stage amount - NSC stageAmount
nullSettlementChallengeState.initiateProposal(
wallet, nonce, stageAmount,
activeBalanceAmount.sub(
dscCumulativeTransferAmount.add(dscStageAmount).add(stageAmount)
),
currency,
activeBalanceBlockNumber, walletInitiated
);
}
function _stopChallenge(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
private
{
// Require that there is an unterminated driip settlement challenge proposal
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlementChallengeByPayment.sol:481]");
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlementChallengeByPayment.sol:482]");
// Terminate driip settlement challenge proposal
nullSettlementChallengeState.terminateProposal(
wallet, currency, walletTerminated
);
}
function _externalProperties(address wallet, MonetaryTypesLib.Currency memory currency)
private
view
returns (
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) {
(activeBalanceAmount, activeBalanceBlockNumber) = balanceTracker.fungibleActiveRecord(
wallet, currency
);
if (driipSettlementChallengeState.hasProposal(wallet, currency)) {
if (!driipSettlementChallengeState.hasProposalTerminated(wallet, currency)) {
dscCumulativeTransferAmount = driipSettlementChallengeState.proposalCumulativeTransferAmount(wallet, currency);
dscStageAmount = driipSettlementChallengeState.proposalStageAmount(wallet, currency);
}
nonce = driipSettlementChallengeState.proposalNonce(wallet, currency);
}
if (nullSettlementChallengeState.hasProposal(wallet, currency))
nonce = nonce.clampMin(nullSettlementChallengeState.proposalNonce(wallet, currency));
}
} | Get the subset of registered signers in the given 0 based index range low The lower inclusive index up The upper inclusive index return The subset of registered signers | function signersByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < signers.length, "No signers found [SignerManager.sol:101]");
require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]");
up = up.clampMax(signers.length - 1);
address[] memory _signers = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_signers[i - low] = signers[i];
return _signers;
}
| 12,574,579 |
./partial_match/1/0x99937d00F549e222fe8f144C12A161707a766F4c/sources/TnmtToken.sol | Set/Update data for a Tnmt/ | function updateTnmtData(
uint256 _tnmtId,
uint8 _noColors,
uint256 _monkeyId,
bool _hFlip,
bool _vFlip,
string memory _evento,
ITnmtLibrary.ColorDec[11] memory _colors,
uint8[1024] calldata _pixels
) public onlyDataPusher returns (uint256) {
require(_exists(_tnmtId), "Token does not exists");
require( _noColors > 0 && _noColors < 11, "Colors: 1 ... 10");
require( tnmtData[_tnmtId].monkeyId == _monkeyId, "Wrong Monkey Id");
if(tnmtData[_tnmtId].updated == false && edits[_tnmtId].editor != address(0)) {
bool editorPay = false;
if(IMonkeySvgGen(svgGen).editColorsAreValid(minColorDifValue, edits[_tnmtId].manyEdits, edits[_tnmtId].colors, _colors)) {
editorPay = IMonkeySplitter(splitter).approveEditorPay( tnmtData[_tnmtId].auctionId, edits[_tnmtId].editor);
editorPay = IMonkeySplitter(splitter).denyEditorPay(tnmtData[_tnmtId].auctionId,edits[_tnmtId].editor);
delete edits[_tnmtId];
}
require(editorPay, "Something went wrong releasing payments");
}
for (uint8 i = 0; i < _noColors; i++) {
require(_colors[i].colorId < 10, "Color Id: 0-9");
tnmtData[_tnmtId].colors[i] = _colors[i];
}
if(keccak256(abi.encodePacked(_evento)) != keccak256(abi.encodePacked(""))) {
tnmtData[_tnmtId].colors[10] = _colors[10];
}
tnmtData[_tnmtId].noColors = _noColors;
tnmtData[_tnmtId].monkeyId = _monkeyId;
tnmtData[_tnmtId].hFlip = _hFlip;
tnmtData[_tnmtId].vFlip = _vFlip;
tnmtData[_tnmtId].evento = _evento;
tnmtData[_tnmtId].updated = true;
pixelsData[_tnmtId] = _pixels;
emit MetadataUpdate(_tnmtId);
return _tnmtId;
}
| 2,661,685 |
./full_match/11155111/0x1E2315519Ad39dFc9E1535125436fB4Fb738b0db/sources/contracts/crowdfunding.sol | string memory _imguint256 minute = 1 minutes;campaign.amountleft = 0; int256[] memory timer = new uint256[](numberOfCampaigns);campaign.img = _img; | function createCampaign(
string memory _title,
string memory _description,
uint256 _target,
uint256 _deadline,
uint256 _expectedInterestRate,
uint256 _stage0time,
uint256 _stage1time,
uint256 _stage2time,
uint256 _stage3time
) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(_deadline>0, "The deadline should be a date in the future.");
campaign.owner = msg.sender;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.expectedInterestRate = _expectedInterestRate;
campaign.status = 1;
campaign.current_stage = 0;
campaign.timer = [_stage0time,_stage1time,_stage2time,_stage3time];
campaign.profit = 0;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 3,806,554 |
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/pool/Math64x64.sol
/*
* Math 64.64 Smart Contract Library. Copyright © 2019 by Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.6.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library Math64x64 {
/**
* @dev Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* @dev Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* @dev Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* @dev Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* @dev Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* @dev Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* @dev Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* @dev Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* @dev Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* @dev Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* @dev Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* @dev Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* @dev Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* @dev Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* @dev Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* @dev Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* @dev Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* @dev Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* @dev Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* @dev Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* @dev Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* @dev Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* @dev Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* @dev Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* @dev Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* @dev Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* @dev Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* @dev Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* @dev Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* @dev Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
// File: contracts/pool/YieldMath.sol
pragma solidity ^0.6.0;
/**
* Ethereum smart contract library implementing Yield Math model.
*/
library YieldMath {
/**
* Calculate the amount of fyDai a user would get for given amount of Dai.
*
* @param daiReserves Dai reserves amount
* @param fyDaiReserves fyDai reserves amount
* @param daiAmount Dai amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param k time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of fyDai a user would get for given amount of Dai
*/
function fyDaiOutForDaiIn (
uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount,
uint128 timeTillMaturity, int128 k, int128 g)
internal pure returns (uint128) {
// t = k * timeTillMaturity
int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity));
// a = (1 - gt)
int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t));
require (a > 0, "YieldMath: Too far from maturity");
// xdx = daiReserves + daiAmount
uint256 xdx = uint256 (daiReserves) + uint256 (daiAmount);
require (xdx < 0x100000000000000000000000000000000, "YieldMath: Too much Dai in");
uint256 sum =
pow (daiReserves, uint128 (a), 0x10000000000000000) +
pow (fyDaiReserves, uint128 (a), 0x10000000000000000) -
pow (uint128(xdx), uint128 (a), 0x10000000000000000);
require (sum < 0x100000000000000000000000000000000, "YieldMath: Insufficient fyDai reserves");
uint256 result = fyDaiReserves - pow (uint128 (sum), 0x10000000000000000, uint128 (a));
require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error");
result = result > 1e12 ? result - 1e12 : 0; // Substract error guard, flooring the result at zero
return uint128 (result);
}
/**
* Calculate the amount of Dai a user would get for certain amount of fyDai.
*
* @param daiReserves Dai reserves amount
* @param fyDaiReserves fyDai reserves amount
* @param fyDaiAmount fyDai amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param k time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of Dai a user would get for given amount of fyDai
*/
function daiOutForFYDaiIn (
uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount,
uint128 timeTillMaturity, int128 k, int128 g)
internal pure returns (uint128) {
// t = k * timeTillMaturity
int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity));
// a = (1 - gt)
int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t));
require (a > 0, "YieldMath: Too far from maturity");
// ydy = fyDaiReserves + fyDaiAmount;
uint256 ydy = uint256 (fyDaiReserves) + uint256 (fyDaiAmount);
require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai in");
uint256 sum =
pow (uint128 (daiReserves), uint128 (a), 0x10000000000000000) -
pow (uint128 (ydy), uint128 (a), 0x10000000000000000) +
pow (fyDaiReserves, uint128 (a), 0x10000000000000000);
require (sum < 0x100000000000000000000000000000000, "YieldMath: Insufficient Dai reserves");
uint256 result =
daiReserves -
pow (uint128 (sum), 0x10000000000000000, uint128 (a));
require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error");
result = result > 1e12 ? result - 1e12 : 0; // Substract error guard, flooring the result at zero
return uint128 (result);
}
/**
* Calculate the amount of fyDai a user could sell for given amount of Dai.
*
* @param daiReserves Dai reserves amount
* @param fyDaiReserves fyDai reserves amount
* @param daiAmount Dai amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param k time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of fyDai a user could sell for given amount of Dai
*/
function fyDaiInForDaiOut (
uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount,
uint128 timeTillMaturity, int128 k, int128 g)
internal pure returns (uint128) {
// t = k * timeTillMaturity
int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity));
// a = (1 - gt)
int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t));
require (a > 0, "YieldMath: Too far from maturity");
// xdx = daiReserves - daiAmount
uint256 xdx = uint256 (daiReserves) - uint256 (daiAmount);
require (xdx < 0x100000000000000000000000000000000, "YieldMath: Too much Dai out");
uint256 sum =
pow (uint128 (daiReserves), uint128 (a), 0x10000000000000000) +
pow (fyDaiReserves, uint128 (a), 0x10000000000000000) -
pow (uint128 (xdx), uint128 (a), 0x10000000000000000);
require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting fyDai reserves too high");
uint256 result = pow (uint128 (sum), 0x10000000000000000, uint128 (a)) - fyDaiReserves;
require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error");
result = result < type(uint128).max - 1e12 ? result + 1e12 : type(uint128).max; // Add error guard, ceiling the result at max
return uint128 (result);
}
/**
* Calculate the amount of Dai a user would have to pay for certain amount of
* fyDai.
*
* @param daiReserves Dai reserves amount
* @param fyDaiReserves fyDai reserves amount
* @param fyDaiAmount fyDai amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param k time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of Dai a user would have to pay for given amount of
* fyDai
*/
function daiInForFYDaiOut (
uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount,
uint128 timeTillMaturity, int128 k, int128 g)
internal pure returns (uint128) {
// a = (1 - g * k * timeTillMaturity)
int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity))));
require (a > 0, "YieldMath: Too far from maturity");
// ydy = fyDaiReserves - fyDaiAmount;
uint256 ydy = uint256 (fyDaiReserves) - uint256 (fyDaiAmount);
require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai out");
uint256 sum =
pow (daiReserves, uint128 (a), 0x10000000000000000) +
pow (fyDaiReserves, uint128 (a), 0x10000000000000000) -
pow (uint128 (ydy), uint128 (a), 0x10000000000000000);
require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting Dai reserves too high");
uint256 result =
pow (uint128 (sum), 0x10000000000000000, uint128 (a)) -
daiReserves;
require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error");
result = result < type(uint128).max - 1e12 ? result + 1e12 : type(uint128).max; // Add error guard, ceiling the result at max
return uint128 (result);
}
/**
* Raise given number x into power specified as a simple fraction y/z and then
* multiply the result by the normalization factor 2^(128 * (1 - y/z)).
* Revert if z is zero, or if both x and y are zeros.
*
* @param x number to raise into given power y/z
* @param y numerator of the power to raise x into
* @param z denominator of the power to raise x into
* @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z))
*/
function pow (uint128 x, uint128 y, uint128 z)
internal pure returns (uint256) {
require (z != 0);
if (x == 0) {
require (y != 0);
return 0;
} else {
uint256 l =
uint256 (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2 (x)) * y / z;
if (l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0;
else return uint256 (pow_2 (uint128 (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l)));
}
}
/**
* Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert
* in case x is zero.
*
* @param x number to calculate base 2 logarithm of
* @return base 2 logarithm of x, multiplied by 2^121
*/
function log_2 (uint128 x)
internal pure returns (uint128) {
require (x != 0);
uint b = x;
uint l = 0xFE000000000000000000000000000000;
if (b < 0x10000000000000000) {l -= 0x80000000000000000000000000000000; b <<= 64;}
if (b < 0x1000000000000000000000000) {l -= 0x40000000000000000000000000000000; b <<= 32;}
if (b < 0x10000000000000000000000000000) {l -= 0x20000000000000000000000000000000; b <<= 16;}
if (b < 0x1000000000000000000000000000000) {l -= 0x10000000000000000000000000000000; b <<= 8;}
if (b < 0x10000000000000000000000000000000) {l -= 0x8000000000000000000000000000000; b <<= 4;}
if (b < 0x40000000000000000000000000000000) {l -= 0x4000000000000000000000000000000; b <<= 2;}
if (b < 0x80000000000000000000000000000000) {l -= 0x2000000000000000000000000000000; b <<= 1;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000;}
/* Precision reduced to 64 bits
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;}
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) l |= 0x1;
*/
return uint128 (l);
}
/**
* Calculate 2 raised into given power.
*
* @param x power to raise 2 into, multiplied by 2^121
* @return 2 raised into given power
*/
function pow_2 (uint128 x)
internal pure returns (uint128) {
uint r = 0x80000000000000000000000000000000;
if (x & 0x1000000000000000000000000000000 > 0) r = r * 0xb504f333f9de6484597d89b3754abe9f >> 127;
if (x & 0x800000000000000000000000000000 > 0) r = r * 0x9837f0518db8a96f46ad23182e42f6f6 >> 127;
if (x & 0x400000000000000000000000000000 > 0) r = r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90 >> 127;
if (x & 0x200000000000000000000000000000 > 0) r = r * 0x85aac367cc487b14c5c95b8c2154c1b2 >> 127;
if (x & 0x100000000000000000000000000000 > 0) r = r * 0x82cd8698ac2ba1d73e2a475b46520bff >> 127;
if (x & 0x80000000000000000000000000000 > 0) r = r * 0x8164d1f3bc0307737be56527bd14def4 >> 127;
if (x & 0x40000000000000000000000000000 > 0) r = r * 0x80b1ed4fd999ab6c25335719b6e6fd20 >> 127;
if (x & 0x20000000000000000000000000000 > 0) r = r * 0x8058d7d2d5e5f6b094d589f608ee4aa2 >> 127;
if (x & 0x10000000000000000000000000000 > 0) r = r * 0x802c6436d0e04f50ff8ce94a6797b3ce >> 127;
if (x & 0x8000000000000000000000000000 > 0) r = r * 0x8016302f174676283690dfe44d11d008 >> 127;
if (x & 0x4000000000000000000000000000 > 0) r = r * 0x800b179c82028fd0945e54e2ae18f2f0 >> 127;
if (x & 0x2000000000000000000000000000 > 0) r = r * 0x80058baf7fee3b5d1c718b38e549cb93 >> 127;
if (x & 0x1000000000000000000000000000 > 0) r = r * 0x8002c5d00fdcfcb6b6566a58c048be1f >> 127;
if (x & 0x800000000000000000000000000 > 0) r = r * 0x800162e61bed4a48e84c2e1a463473d9 >> 127;
if (x & 0x400000000000000000000000000 > 0) r = r * 0x8000b17292f702a3aa22beacca949013 >> 127;
if (x & 0x200000000000000000000000000 > 0) r = r * 0x800058b92abbae02030c5fa5256f41fe >> 127;
if (x & 0x100000000000000000000000000 > 0) r = r * 0x80002c5c8dade4d71776c0f4dbea67d6 >> 127;
if (x & 0x80000000000000000000000000 > 0) r = r * 0x8000162e44eaf636526be456600bdbe4 >> 127;
if (x & 0x40000000000000000000000000 > 0) r = r * 0x80000b1721fa7c188307016c1cd4e8b6 >> 127;
if (x & 0x20000000000000000000000000 > 0) r = r * 0x8000058b90de7e4cecfc487503488bb1 >> 127;
if (x & 0x10000000000000000000000000 > 0) r = r * 0x800002c5c8678f36cbfce50a6de60b14 >> 127;
if (x & 0x8000000000000000000000000 > 0) r = r * 0x80000162e431db9f80b2347b5d62e516 >> 127;
if (x & 0x4000000000000000000000000 > 0) r = r * 0x800000b1721872d0c7b08cf1e0114152 >> 127;
if (x & 0x2000000000000000000000000 > 0) r = r * 0x80000058b90c1aa8a5c3736cb77e8dff >> 127;
if (x & 0x1000000000000000000000000 > 0) r = r * 0x8000002c5c8605a4635f2efc2362d978 >> 127;
if (x & 0x800000000000000000000000 > 0) r = r * 0x800000162e4300e635cf4a109e3939bd >> 127;
if (x & 0x400000000000000000000000 > 0) r = r * 0x8000000b17217ff81bef9c551590cf83 >> 127;
if (x & 0x200000000000000000000000 > 0) r = r * 0x800000058b90bfdd4e39cd52c0cfa27c >> 127;
if (x & 0x100000000000000000000000 > 0) r = r * 0x80000002c5c85fe6f72d669e0e76e411 >> 127;
if (x & 0x80000000000000000000000 > 0) r = r * 0x8000000162e42ff18f9ad35186d0df28 >> 127;
if (x & 0x40000000000000000000000 > 0) r = r * 0x80000000b17217f84cce71aa0dcfffe7 >> 127;
if (x & 0x20000000000000000000000 > 0) r = r * 0x8000000058b90bfc07a77ad56ed22aaa >> 127;
if (x & 0x10000000000000000000000 > 0) r = r * 0x800000002c5c85fdfc23cdead40da8d6 >> 127;
if (x & 0x8000000000000000000000 > 0) r = r * 0x80000000162e42fefc25eb1571853a66 >> 127;
if (x & 0x4000000000000000000000 > 0) r = r * 0x800000000b17217f7d97f692baacded5 >> 127;
if (x & 0x2000000000000000000000 > 0) r = r * 0x80000000058b90bfbead3b8b5dd254d7 >> 127;
if (x & 0x1000000000000000000000 > 0) r = r * 0x8000000002c5c85fdf4eedd62f084e67 >> 127;
if (x & 0x800000000000000000000 > 0) r = r * 0x800000000162e42fefa58aef378bf586 >> 127;
if (x & 0x400000000000000000000 > 0) r = r * 0x8000000000b17217f7d24a78a3c7ef02 >> 127;
if (x & 0x200000000000000000000 > 0) r = r * 0x800000000058b90bfbe9067c93e474a6 >> 127;
if (x & 0x100000000000000000000 > 0) r = r * 0x80000000002c5c85fdf47b8e5a72599f >> 127;
if (x & 0x80000000000000000000 > 0) r = r * 0x8000000000162e42fefa3bdb315934a2 >> 127;
if (x & 0x40000000000000000000 > 0) r = r * 0x80000000000b17217f7d1d7299b49c46 >> 127;
if (x & 0x20000000000000000000 > 0) r = r * 0x8000000000058b90bfbe8e9a8d1c4ea0 >> 127;
if (x & 0x10000000000000000000 > 0) r = r * 0x800000000002c5c85fdf4745969ea76f >> 127;
if (x & 0x8000000000000000000 > 0) r = r * 0x80000000000162e42fefa3a0df5373bf >> 127;
if (x & 0x4000000000000000000 > 0) r = r * 0x800000000000b17217f7d1cff4aac1e1 >> 127;
if (x & 0x2000000000000000000 > 0) r = r * 0x80000000000058b90bfbe8e7db95a2f1 >> 127;
if (x & 0x1000000000000000000 > 0) r = r * 0x8000000000002c5c85fdf473e61ae1f8 >> 127;
if (x & 0x800000000000000000 > 0) r = r * 0x800000000000162e42fefa39f121751c >> 127;
if (x & 0x400000000000000000 > 0) r = r * 0x8000000000000b17217f7d1cf815bb96 >> 127;
if (x & 0x200000000000000000 > 0) r = r * 0x800000000000058b90bfbe8e7bec1e0d >> 127;
if (x & 0x100000000000000000 > 0) r = r * 0x80000000000002c5c85fdf473dee5f17 >> 127;
if (x & 0x80000000000000000 > 0) r = r * 0x8000000000000162e42fefa39ef5438f >> 127;
if (x & 0x40000000000000000 > 0) r = r * 0x80000000000000b17217f7d1cf7a26c8 >> 127;
if (x & 0x20000000000000000 > 0) r = r * 0x8000000000000058b90bfbe8e7bcf4a4 >> 127;
if (x & 0x10000000000000000 > 0) r = r * 0x800000000000002c5c85fdf473de72a2 >> 127;
/* Precision reduced to 64 bits
if (x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127;
if (x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127;
if (x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127;
if (x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127;
if (x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127;
if (x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127;
if (x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127;
if (x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127;
if (x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127;
if (x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127;
if (x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127;
if (x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127;
if (x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127;
if (x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127;
if (x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127;
if (x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127;
if (x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127;
if (x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127;
if (x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127;
if (x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127;
if (x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127;
if (x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127;
if (x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127;
if (x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127;
if (x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127;
if (x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127;
if (x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127;
if (x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127;
if (x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127;
if (x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127;
if (x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127;
if (x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127;
if (x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127;
if (x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127;
if (x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127;
if (x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127;
if (x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127;
if (x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127;
if (x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127;
if (x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127;
if (x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127;
if (x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127;
if (x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127;
if (x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127;
if (x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127;
if (x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127;
if (x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127;
if (x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127;
if (x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127;
if (x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127;
if (x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127;
if (x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127;
if (x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127;
if (x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127;
if (x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127;
if (x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127;
if (x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127;
if (x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127;
if (x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127;
if (x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127;
if (x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127;
if (x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127;
if (x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127;
if (x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127;
*/
r >>= 127 - (x >> 121);
return uint128 (r);
}
}
// File: contracts/interfaces/IDelegable.sol
pragma solidity ^0.6.10;
interface IDelegable {
function addDelegate(address) external;
function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external;
}
// File: contracts/helpers/Delegable.sol
pragma solidity ^0.6.10;
/// @dev Delegable enables users to delegate their account management to other users.
/// Delegable implements addDelegateBySignature, to add delegates using a signature instead of a separate transaction.
contract Delegable is IDelegable {
event Delegate(address indexed user, address indexed delegate, bool enabled);
// keccak256("Signature(address user,address delegate,uint256 nonce,uint256 deadline)");
bytes32 public immutable SIGNATURE_TYPEHASH = 0x0d077601844dd17f704bafff948229d27f33b57445915754dfe3d095fda2beb7;
bytes32 public immutable DELEGABLE_DOMAIN;
mapping(address => uint) public signatureCount;
mapping(address => mapping(address => bool)) public delegated;
constructor () public {
uint256 chainId;
assembly {
chainId := chainid()
}
DELEGABLE_DOMAIN = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes('Yield')),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
/// @dev Require that msg.sender is the account holder or a delegate
modifier onlyHolderOrDelegate(address holder, string memory errorMessage) {
require(
msg.sender == holder || delegated[holder][msg.sender],
errorMessage
);
_;
}
/// @dev Enable a delegate to act on the behalf of caller
function addDelegate(address delegate) public override {
_addDelegate(msg.sender, delegate);
}
/// @dev Stop a delegate from acting on the behalf of caller
function revokeDelegate(address delegate) public {
_revokeDelegate(msg.sender, delegate);
}
/// @dev Add a delegate through an encoded signature
function addDelegateBySignature(address user, address delegate, uint deadline, uint8 v, bytes32 r, bytes32 s) public override {
require(deadline >= block.timestamp, 'Delegable: Signature expired');
bytes32 hashStruct = keccak256(
abi.encode(
SIGNATURE_TYPEHASH,
user,
delegate,
signatureCount[user]++,
deadline
)
);
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DELEGABLE_DOMAIN,
hashStruct
)
);
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0) && signer == user,
'Delegable: Invalid signature'
);
_addDelegate(user, delegate);
}
/// @dev Enable a delegate to act on the behalf of an user
function _addDelegate(address user, address delegate) internal {
require(!delegated[user][delegate], "Delegable: Already delegated");
delegated[user][delegate] = true;
emit Delegate(user, delegate, true);
}
/// @dev Stop a delegate from acting on the behalf of an user
function _revokeDelegate(address user, address delegate) internal {
require(delegated[user][delegate], "Delegable: Already undelegated");
delegated[user][delegate] = false;
emit Delegate(user, delegate, false);
}
}
// File: contracts/interfaces/IERC2612.sol
// Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*/
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
}
// File: contracts/helpers/ERC20Permit.sol
// Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that allows token holders to use their tokens
* without sending any transactions by setting {IERC20-allowance} with a
* signature using the {permit} method, and then spend them via
* {IERC20-transferFrom}.
*
* The {permit} signature mechanism conforms to the {IERC2612} interface.
*/
abstract contract ERC20Permit is ERC20, IERC2612 {
mapping (address => uint256) public override nonces;
bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public immutable DOMAIN_SEPARATOR;
constructor(string memory name_, string memory symbol_) internal ERC20(name_, symbol_) {
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)
)
);
}
/**
* @dev See {IERC2612-permit}.
*
* In cases where the free option is not a concern, deadline can simply be
* set to uint(-1), so it should be seen as an optional parameter
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
require(deadline >= block.timestamp, "ERC20Permit: expired deadline");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
amount,
nonces[owner]++,
deadline
)
);
bytes32 hash = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
hashStruct
)
);
address signer = ecrecover(hash, v, r, s);
require(
signer != address(0) && signer == owner,
"ERC20Permit: invalid signature"
);
_approve(owner, spender, amount);
}
}
// File: contracts/interfaces/IPot.sol
pragma solidity ^0.6.10;
/// @dev interface for the pot contract from MakerDao
/// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol
interface IPot {
function chi() external view returns (uint256);
function pie(address) external view returns (uint256); // Not a function, but a public variable.
function rho() external returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/interfaces/IFYDai.sol
pragma solidity ^0.6.10;
interface IFYDai is IERC20, IERC2612 {
function isMature() external view returns(bool);
function maturity() external view returns(uint);
function chi0() external view returns(uint);
function rate0() external view returns(uint);
function chiGrowth() external view returns(uint);
function rateGrowth() external view returns(uint);
function mature() external;
function unlocked() external view returns (uint);
function mint(address, uint) external;
function burn(address, uint) external;
function flashMint(uint, bytes calldata) external;
function redeem(address, address, uint256) external returns (uint256);
// function transfer(address, uint) external returns (bool);
// function transferFrom(address, address, uint) external returns (bool);
// function approve(address, uint) external returns (bool);
}
// File: contracts/interfaces/IPool.sol
pragma solidity ^0.6.10;
interface IPool is IDelegable, IERC20, IERC2612 {
function dai() external view returns(IERC20);
function fyDai() external view returns(IFYDai);
function getDaiReserves() external view returns(uint128);
function getFYDaiReserves() external view returns(uint128);
function sellDai(address from, address to, uint128 daiIn) external returns(uint128);
function buyDai(address from, address to, uint128 daiOut) external returns(uint128);
function sellFYDai(address from, address to, uint128 fyDaiIn) external returns(uint128);
function buyFYDai(address from, address to, uint128 fyDaiOut) external returns(uint128);
function sellDaiPreview(uint128 daiIn) external view returns(uint128);
function buyDaiPreview(uint128 daiOut) external view returns(uint128);
function sellFYDaiPreview(uint128 fyDaiIn) external view returns(uint128);
function buyFYDaiPreview(uint128 fyDaiOut) external view returns(uint128);
function mint(address from, address to, uint256 daiOffered) external returns (uint256);
function burn(address from, address to, uint256 tokensBurned) external returns (uint256, uint256);
}
// File: contracts/pool/Pool.sol
pragma solidity ^0.6.10;
/// @dev The Pool contract exchanges Dai for fyDai at a price defined by a specific formula.
contract Pool is IPool, Delegable(), ERC20Permit {
event Trade(uint256 maturity, address indexed from, address indexed to, int256 daiTokens, int256 fyDaiTokens);
event Liquidity(uint256 maturity, address indexed from, address indexed to, int256 daiTokens, int256 fyDaiTokens, int256 poolTokens);
int128 constant public k = int128(uint256((1 << 64)) / 126144000); // 1 / Seconds in 4 years, in 64.64
int128 constant public g1 = int128(uint256((950 << 64)) / 1000); // To be used when selling Dai to the pool. All constants are `ufixed`, to divide them they must be converted to uint256
int128 constant public g2 = int128(uint256((1000 << 64)) / 950); // To be used when selling fyDai to the pool. All constants are `ufixed`, to divide them they must be converted to uint256
uint128 immutable public maturity;
IERC20 public override dai;
IFYDai public override fyDai;
constructor(address dai_, address fyDai_, string memory name_, string memory symbol_)
public
ERC20Permit(name_, symbol_)
{
dai = IERC20(dai_);
fyDai = IFYDai(fyDai_);
maturity = toUint128(fyDai.maturity());
}
/// @dev Trading can only be done before maturity
modifier beforeMaturity() {
require(
now < maturity,
"Pool: Too late"
);
_;
}
/// @dev Overflow-protected addition, from OpenZeppelin
function add(uint128 a, uint128 b)
internal pure returns (uint128)
{
uint128 c = a + b;
require(c >= a, "Pool: Dai reserves too high");
return c;
}
/// @dev Overflow-protected substraction, from OpenZeppelin
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "Pool: fyDai reserves too low");
uint128 c = a - b;
return c;
}
/// @dev Safe casting from uint256 to uint128
function toUint128(uint256 x) internal pure returns(uint128) {
require(
x <= type(uint128).max,
"Pool: Cast overflow"
);
return uint128(x);
}
/// @dev Safe casting from uint256 to int256
function toInt256(uint256 x) internal pure returns(int256) {
require(
x <= uint256(type(int256).max),
"Pool: Cast overflow"
);
return int256(x);
}
/// @dev Mint initial liquidity tokens.
/// The liquidity provider needs to have called `dai.approve`
/// @param daiIn The initial Dai liquidity to provide.
function init(uint256 daiIn)
internal
beforeMaturity
returns (uint256)
{
require(
totalSupply() == 0,
"Pool: Already initialized"
);
// no fyDai transferred, because initial fyDai deposit is entirely virtual
dai.transferFrom(msg.sender, address(this), daiIn);
_mint(msg.sender, daiIn);
emit Liquidity(maturity, msg.sender, msg.sender, -toInt256(daiIn), 0, toInt256(daiIn));
return daiIn;
}
/// @dev Mint liquidity tokens in exchange for adding dai and fyDai
/// The liquidity provider needs to have called `dai.approve` and `fyDai.approve`.
/// @param from Wallet providing the dai and fyDai. Must have approved the operator with `pool.addDelegate(operator)`.
/// @param to Wallet receiving the minted liquidity tokens.
/// @param daiOffered Amount of `dai` being invested, an appropriate amount of `fyDai` to be invested alongside will be calculated and taken by this function from the caller.
/// @return The amount of liquidity tokens minted.
function mint(address from, address to, uint256 daiOffered)
external override
onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate")
returns (uint256)
{
uint256 supply = totalSupply();
if (supply == 0) return init(daiOffered);
uint256 daiReserves = dai.balanceOf(address(this));
// use the actual reserves rather than the virtual reserves
uint256 fyDaiReserves = fyDai.balanceOf(address(this));
uint256 tokensMinted = supply.mul(daiOffered).div(daiReserves);
uint256 fyDaiRequired = fyDaiReserves.mul(tokensMinted).div(supply);
require(daiReserves.add(daiOffered) <= type(uint128).max); // fyDaiReserves can't go over type(uint128).max
require(supply.add(fyDaiReserves.add(fyDaiRequired)) <= type(uint128).max); // fyDaiReserves can't go over type(uint128).max
require(dai.transferFrom(from, address(this), daiOffered));
require(fyDai.transferFrom(from, address(this), fyDaiRequired));
_mint(to, tokensMinted);
emit Liquidity(maturity, from, to, -toInt256(daiOffered), -toInt256(fyDaiRequired), toInt256(tokensMinted));
return tokensMinted;
}
/// @dev Burn liquidity tokens in exchange for dai and fyDai.
/// The liquidity provider needs to have called `pool.approve`.
/// @param from Wallet providing the liquidity tokens. Must have approved the operator with `pool.addDelegate(operator)`.
/// @param to Wallet receiving the dai and fyDai.
/// @param tokensBurned Amount of liquidity tokens being burned.
/// @return The amount of reserve tokens returned (daiTokens, fyDaiTokens).
function burn(address from, address to, uint256 tokensBurned)
external override
onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate")
returns (uint256, uint256)
{
uint256 supply = totalSupply();
uint256 daiReserves = dai.balanceOf(address(this));
// use the actual reserves rather than the virtual reserves
uint256 daiReturned;
uint256 fyDaiReturned;
{ // avoiding stack too deep
uint256 fyDaiReserves = fyDai.balanceOf(address(this));
daiReturned = tokensBurned.mul(daiReserves).div(supply);
fyDaiReturned = tokensBurned.mul(fyDaiReserves).div(supply);
}
_burn(from, tokensBurned);
dai.transfer(to, daiReturned);
fyDai.transfer(to, fyDaiReturned);
emit Liquidity(maturity, from, to, toInt256(daiReturned), toInt256(fyDaiReturned), -toInt256(tokensBurned));
return (daiReturned, fyDaiReturned);
}
/// @dev Sell Dai for fyDai
/// The trader needs to have called `dai.approve`
/// @param from Wallet providing the dai being sold. Must have approved the operator with `pool.addDelegate(operator)`.
/// @param to Wallet receiving the fyDai being bought
/// @param daiIn Amount of dai being sold that will be taken from the user's wallet
/// @return Amount of fyDai that will be deposited on `to` wallet
function sellDai(address from, address to, uint128 daiIn)
external override
onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate")
returns(uint128)
{
uint128 fyDaiOut = sellDaiPreview(daiIn);
dai.transferFrom(from, address(this), daiIn);
fyDai.transfer(to, fyDaiOut);
emit Trade(maturity, from, to, -toInt256(daiIn), toInt256(fyDaiOut));
return fyDaiOut;
}
/// @dev Returns how much fyDai would be obtained by selling `daiIn` dai
/// @param daiIn Amount of dai hypothetically sold.
/// @return Amount of fyDai hypothetically bought.
function sellDaiPreview(uint128 daiIn)
public view override
beforeMaturity
returns(uint128)
{
uint128 daiReserves = getDaiReserves();
uint128 fyDaiReserves = getFYDaiReserves();
uint128 fyDaiOut = YieldMath.fyDaiOutForDaiIn(
daiReserves,
fyDaiReserves,
daiIn,
toUint128(maturity - now), // This can't be called after maturity
k,
g1
);
require(
sub(fyDaiReserves, fyDaiOut) >= add(daiReserves, daiIn),
"Pool: fyDai reserves too low"
);
return fyDaiOut;
}
/// @dev Buy Dai for fyDai
/// The trader needs to have called `fyDai.approve`
/// @param from Wallet providing the fyDai being sold. Must have approved the operator with `pool.addDelegate(operator)`.
/// @param to Wallet receiving the dai being bought
/// @param daiOut Amount of dai being bought that will be deposited in `to` wallet
/// @return Amount of fyDai that will be taken from `from` wallet
function buyDai(address from, address to, uint128 daiOut)
external override
onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate")
returns(uint128)
{
uint128 fyDaiIn = buyDaiPreview(daiOut);
fyDai.transferFrom(from, address(this), fyDaiIn);
dai.transfer(to, daiOut);
emit Trade(maturity, from, to, toInt256(daiOut), -toInt256(fyDaiIn));
return fyDaiIn;
}
/// @dev Returns how much fyDai would be required to buy `daiOut` dai.
/// @param daiOut Amount of dai hypothetically desired.
/// @return Amount of fyDai hypothetically required.
function buyDaiPreview(uint128 daiOut)
public view override
beforeMaturity
returns(uint128)
{
return YieldMath.fyDaiInForDaiOut(
getDaiReserves(),
getFYDaiReserves(),
daiOut,
toUint128(maturity - now), // This can't be called after maturity
k,
g2
);
}
/// @dev Sell fyDai for Dai
/// The trader needs to have called `fyDai.approve`
/// @param from Wallet providing the fyDai being sold. Must have approved the operator with `pool.addDelegate(operator)`.
/// @param to Wallet receiving the dai being bought
/// @param fyDaiIn Amount of fyDai being sold that will be taken from the user's wallet
/// @return Amount of dai that will be deposited on `to` wallet
function sellFYDai(address from, address to, uint128 fyDaiIn)
external override
onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate")
returns(uint128)
{
uint128 daiOut = sellFYDaiPreview(fyDaiIn);
fyDai.transferFrom(from, address(this), fyDaiIn);
dai.transfer(to, daiOut);
emit Trade(maturity, from, to, toInt256(daiOut), -toInt256(fyDaiIn));
return daiOut;
}
/// @dev Returns how much dai would be obtained by selling `fyDaiIn` fyDai.
/// @param fyDaiIn Amount of fyDai hypothetically sold.
/// @return Amount of Dai hypothetically bought.
function sellFYDaiPreview(uint128 fyDaiIn)
public view override
beforeMaturity
returns(uint128)
{
return YieldMath.daiOutForFYDaiIn(
getDaiReserves(),
getFYDaiReserves(),
fyDaiIn,
toUint128(maturity - now), // This can't be called after maturity
k,
g2
);
}
/// @dev Buy fyDai for dai
/// The trader needs to have called `dai.approve`
/// @param from Wallet providing the dai being sold. Must have approved the operator with `pool.addDelegate(operator)`.
/// @param to Wallet receiving the fyDai being bought
/// @param fyDaiOut Amount of fyDai being bought that will be deposited in `to` wallet
/// @return Amount of dai that will be taken from `from` wallet
function buyFYDai(address from, address to, uint128 fyDaiOut)
external override
onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate")
returns(uint128)
{
uint128 daiIn = buyFYDaiPreview(fyDaiOut);
dai.transferFrom(from, address(this), daiIn);
fyDai.transfer(to, fyDaiOut);
emit Trade(maturity, from, to, -toInt256(daiIn), toInt256(fyDaiOut));
return daiIn;
}
/// @dev Returns how much dai would be required to buy `fyDaiOut` fyDai.
/// @param fyDaiOut Amount of fyDai hypothetically desired.
/// @return Amount of Dai hypothetically required.
function buyFYDaiPreview(uint128 fyDaiOut)
public view override
beforeMaturity
returns(uint128)
{
uint128 daiReserves = getDaiReserves();
uint128 fyDaiReserves = getFYDaiReserves();
uint128 daiIn = YieldMath.daiInForFYDaiOut(
daiReserves,
fyDaiReserves,
fyDaiOut,
toUint128(maturity - now), // This can't be called after maturity
k,
g1
);
require(
sub(fyDaiReserves, fyDaiOut) >= add(daiReserves, daiIn),
"Pool: fyDai reserves too low"
);
return daiIn;
}
/// @dev Returns the "virtual" fyDai reserves
function getFYDaiReserves()
public view override
returns(uint128)
{
return toUint128(fyDai.balanceOf(address(this)).add(totalSupply()));
}
/// @dev Returns the Dai reserves
function getDaiReserves()
public view override
returns(uint128)
{
return toUint128(dai.balanceOf(address(this)));
}
} | Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert in case x is zero. x number to calculate base 2 logarithm of return base 2 logarithm of x, multiplied by 2^121/ | function log_2 (uint128 x)
internal pure returns (uint128) {
require (x != 0);
uint b = x;
uint l = 0xFE000000000000000000000000000000;
b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) l |= 0x1;
return uint128 (l);
| 392,437 |
./full_match/1/0x8c1CfaE7866fA2CD4C82fEa9a660cfB0FAa7578F/sources/contracts/CErc721.sol | Sender borrows assets from the protocol to their own address borrowAmount The amount of the underlying asset to borrow return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function borrow(uint borrowAmount) external override returns (uint) {
require(false);
return borrowInternal(borrowAmount);
}
| 2,944,591 |
pragma solidity ^0.4.24;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
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 BlockchainMoneyEngine is Pausable {
address public owner;
// 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 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
*/
function BlockchainMoneyEngine(
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
owner = msg.sender;
}
function setName(string _name)
onlyOwner()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyOwner()
public
{
symbol = _symbol;
}
/**
* 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);
}
function destruct() public {
if (owner == msg.sender) {
selfdestruct(owner);
}
}
/**
* 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 whenNotPaused {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public whenNotPaused
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* 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;
}
} | Transfer tokens from other address Send `_value` tokens to `_to` on behalf of `_from` _from The address of the sender _to The address of the recipient _value the amount to send/ | function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) {
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| 14,758,248 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.0;
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 IERC4626Vault is IERC20 {
/// @notice The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing
function asset() external view returns (address assetTokenAddress);
/// @notice Total amount of the underlying asset that is “managed” by Vault
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.
* @param assets The amount of underlying assets to be convert to vault shares.
* @return shares The amount of vault shares converted from the underlying assets.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.
* @param shares The amount of vault shares to be converted to the underlying assets.
* @return assets The amount of underlying assets converted from the vault shares.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @notice The maximum number of underlying assets that caller can deposit.
* @param caller Account that the assets will be transferred from.
* @return maxAssets The maximum amount of underlying assets the caller can deposit.
*/
function maxDeposit(address caller) external view returns (uint256 maxAssets);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be transferred.
* @return shares The amount of vault shares that will be minted.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.
* @param assets The amount of underlying assets to be transferred to the vault.
* @param receiver The account that the vault shares will be minted to.
* @return shares The amount of vault shares that were minted.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @notice The maximum number of vault shares that caller can mint.
* @param caller Account that the underlying assets will be transferred from.
* @return maxShares The maximum amount of vault shares the caller can mint.
*/
function maxMint(address caller) external view returns (uint256 maxShares);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions.
* @param shares The amount of vault shares to be minted.
* @return assets The amount of underlying assests that will be transferred from the caller.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.
* @param shares The amount of vault shares to be minted.
* @param receiver The account the vault shares will be minted to.
* @return assets The amount of underlying assets that were transferred from the caller.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @notice The maximum number of underlying assets that owner can withdraw.
* @param owner Account that owns the vault shares.
* @return maxAssets The maximum amount of underlying assets the owner can withdraw.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be withdrawn.
* @return shares The amount of vault shares that will be burnt.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.
* @param assets The amount of underlying assets to be withdrawn from the vault.
* @param receiver The account that the underlying assets will be transferred to.
* @param owner Account that owns the vault shares to be burnt.
* @return shares The amount of vault shares that were burnt.
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice The maximum number of shares an owner can redeem for underlying assets.
* @param owner Account that owns the vault shares.
* @return maxShares The maximum amount of shares the owner can redeem.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions.
* @param shares The amount of vault shares to be burnt.
* @return assets The amount of underlying assests that will transferred to the receiver.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.
* @param shares The amount of vault shares to be burnt.
* @param receiver The account the underlying assets will be transferred to.
* @param owner The account that owns the vault shares to be burnt.
* @return assets The amount of underlying assets that were transferred to the receiver.
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/*///////////////////////////////////////////////////////////////
Events
//////////////////////////////////////////////////////////////*/
/**
* @dev Emitted when caller has exchanged assets for shares, and transferred those shares to owner.
*
* Note It must be emitted when tokens are deposited into the Vault in ERC4626.mint or ERC4626.deposit methods.
*
*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
/**
* @dev Emitted when sender has exchanged shares for assets, and transferred those assets to receiver.
*
* Note It must be emitted when shares are withdrawn from the Vault in ERC4626.redeem or ERC4626.withdraw methods.
*
*/
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
}
interface IUnwrapper {
// @dev Get bAssetOut status
function getIsBassetOut(
address _masset,
bool _inputIsCredit,
address _output
) external view returns (bool isBassetOut);
/// @dev Estimate output
function getUnwrapOutput(
bool _isBassetOut,
address _router,
address _input,
bool _inputIsCredit,
address _output,
uint256 _amount
) external view returns (uint256 output);
/// @dev Unwrap and send
function unwrapAndSend(
bool _isBassetOut,
address _router,
address _input,
address _output,
uint256 _amount,
uint256 _minAmountOut,
address _beneficiary
) external returns (uint256 outputQuantity);
}
interface ISavingsManager {
/** @dev Admin privs */
function distributeUnallocatedInterest(address _mAsset) external;
/** @dev Liquidator */
function depositLiquidation(address _mAsset, uint256 _liquidation) external;
/** @dev Liquidator */
function collectAndStreamInterest(address _mAsset) external;
/** @dev Public privs */
function collectAndDistributeInterest(address _mAsset) external;
}
interface ISavingsContractV4 is IERC4626Vault {
// DEPRECATED but still backwards compatible
function redeem(uint256 _amount) external returns (uint256 massetReturned);
function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf)
// --------------------------------------------
function depositInterest(uint256 _amount) external; // V1 & V2
function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2
function depositSavings(uint256 _amount, address _beneficiary)
external
returns (uint256 creditsIssued); // V2
function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2
function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2
function exchangeRate() external view returns (uint256); // V1 & V2
function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2
function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2
function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2
// --------------------------------------------
function redeemAndUnwrap(
uint256 _amount,
bool _isCreditAmt,
uint256 _minAmountOut,
address _output,
address _beneficiary,
address _router,
bool _isBassetOut
)
external
returns (
uint256 creditsBurned,
uint256 massetRedeemed,
uint256 outputQuantity
);
function depositSavings(
uint256 _underlying,
address _beneficiary,
address _referrer
) external returns (uint256 creditsIssued);
function deposit(
uint256 assets,
address receiver,
address referrer
) external returns (uint256 shares);
function mint(
uint256 shares,
address receiver,
address referrer
) external returns (uint256 assets);
}
/*
* @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 {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
// constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract ERC205 is Context, IERC20 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - 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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev 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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()] - amount);
}
}
abstract contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
abstract contract InitializableToken is ERC205, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg) internal {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
interface IConnector {
/**
* @notice Deposits the mAsset into the connector
* @param _amount Units of mAsset to receive and deposit
*/
function deposit(uint256 _amount) external;
/**
* @notice Withdraws a specific amount of mAsset from the connector
* @param _amount Units of mAsset to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @notice Withdraws all mAsset from the connector
*/
function withdrawAll() external;
/**
* @notice Returns the available balance in the connector. In connections
* where there is likely to be an initial dip in value due to conservative
* exchange rates (e.g. with Curves `get_virtual_price`), it should return
* max(deposited, balance) to avoid temporary negative yield. Any negative yield
* should be corrected during a withdrawal or over time.
* @return Balance of mAsset in the connector
*/
function checkBalance() external view returns (uint256);
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e38 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
/**
* @title SavingsContract
* @author mStable
* @notice Savings contract uses the ever increasing "exchangeRate" to increase
* the value of the Savers "credits" (ERC20) relative to the amount of additional
* underlying collateral that has been deposited into this contract ("interest")
* @dev VERSION: 2.2
* DATE: 2022-04-08
*/
contract SavingsContract_imbtc_mainnet_22 is
ISavingsContractV4,
Initializable,
InitializableToken,
ImmutableModule
{
using StableMath for uint256;
// Core events for depositing and withdrawing
event ExchangeRateUpdated(uint256 newExchangeRate, uint256 interestCollected);
event SavingsDeposited(address indexed saver, uint256 savingsDeposited, uint256 creditsIssued);
event CreditsRedeemed(
address indexed redeemer,
uint256 creditsRedeemed,
uint256 savingsCredited
);
event AutomaticInterestCollectionSwitched(bool automationEnabled);
// Connector poking
event PokerUpdated(address poker);
event FractionUpdated(uint256 fraction);
event ConnectorUpdated(address connector);
event EmergencyUpdate();
event Poked(uint256 oldBalance, uint256 newBalance, uint256 interestDetected);
event PokedRaw();
// Tracking events
event Referral(address indexed referrer, address beneficiary, uint256 amount);
// Rate between 'savings credits' and underlying
// e.g. 1 credit (1e17) mulTruncate(exchangeRate) = underlying, starts at 10:1
// exchangeRate increases over time
uint256 private constant startingRate = 1e17;
uint256 public override exchangeRate;
// Underlying asset is underlying
IERC20 public immutable underlying;
bool private automateInterestCollection;
// Yield
// Poker is responsible for depositing/withdrawing from connector
address public poker;
// Last time a poke was made
uint256 public lastPoke;
// Last known balance of the connector
uint256 public lastBalance;
// Fraction of capital assigned to the connector (100% = 1e18)
uint256 public fraction;
// Address of the current connector (all IConnectors are mStable validated)
IConnector public connector;
// How often do we allow pokes
uint256 private constant POKE_CADENCE = 4 hours;
// Max APY generated on the capital in the connector
uint256 private constant MAX_APY = 4e18;
uint256 private constant SECONDS_IN_YEAR = 365 days;
// Proxy contract for easy redemption
address public immutable unwrapper;
constructor(
address _nexus,
address _underlying,
address _unwrapper
) ImmutableModule(_nexus) {
require(_underlying != address(0), "mAsset address is zero");
require(_unwrapper != address(0), "Unwrapper address is zero");
underlying = IERC20(_underlying);
unwrapper = _unwrapper;
}
// Add these constants to bytecode at deploytime
function initialize(
address _poker,
string calldata _nameArg,
string calldata _symbolArg
) external initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
require(_poker != address(0), "Invalid poker address");
poker = _poker;
fraction = 2e17;
automateInterestCollection = true;
exchangeRate = startingRate;
}
/** @dev Only the savings managaer (pulled from Nexus) can execute this */
modifier onlySavingsManager() {
require(msg.sender == _savingsManager(), "Only savings manager can execute");
_;
}
/***************************************
VIEW - E
****************************************/
/**
* @dev Returns the underlying balance of a given user
* @param _user Address of the user to check
* @return balance Units of underlying owned by the user
*/
function balanceOfUnderlying(address _user) external view override returns (uint256 balance) {
(balance, ) = _creditsToUnderlying(balanceOf(_user));
}
/**
* @dev Converts a given underlying amount into credits
* @param _underlying Units of underlying
* @return credits Credit units (a.k.a imUSD)
*/
function underlyingToCredits(uint256 _underlying)
external
view
override
returns (uint256 credits)
{
(credits, ) = _underlyingToCredits(_underlying);
}
/**
* @dev Converts a given credit amount into underlying
* @param _credits Units of credits
* @return amount Corresponding underlying amount
*/
function creditsToUnderlying(uint256 _credits) external view override returns (uint256 amount) {
(amount, ) = _creditsToUnderlying(_credits);
}
// Deprecated in favour of `balanceOf(address)`
// Maintained for backwards compatibility
// Returns the credit balance of a given user
function creditBalances(address _user) external view override returns (uint256) {
return balanceOf(_user);
}
/***************************************
INTEREST
****************************************/
/**
* @dev Deposit interest (add to savings) and update exchange rate of contract.
* Exchange rate is calculated as the ratio between new savings q and credits:
* exchange rate = savings / credits
*
* @param _amount Units of underlying to add to the savings vault
*/
function depositInterest(uint256 _amount) external override onlySavingsManager {
require(_amount > 0, "Must deposit something");
// Transfer the interest from sender to here
require(underlying.transferFrom(msg.sender, address(this), _amount), "Must receive tokens");
// Calc new exchange rate, protect against initialisation case
uint256 totalCredits = totalSupply();
if (totalCredits > 0) {
// new exchange rate is relationship between _totalCredits & totalSavings
// _totalCredits * exchangeRate = totalSavings
// exchangeRate = totalSavings/_totalCredits
(uint256 totalCollat, ) = _creditsToUnderlying(totalCredits);
uint256 newExchangeRate = _calcExchangeRate(totalCollat + _amount, totalCredits);
exchangeRate = newExchangeRate;
emit ExchangeRateUpdated(newExchangeRate, _amount);
}
}
/** @dev Enable or disable the automation of fee collection during deposit process */
function automateInterestCollectionFlag(bool _enabled) external onlyGovernor {
automateInterestCollection = _enabled;
emit AutomaticInterestCollectionSwitched(_enabled);
}
/***************************************
DEPOSIT
****************************************/
/**
* @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected
* @param _underlying Units of underlying to deposit into savings vault
* @param _beneficiary Immediately transfer the imUSD token to this beneficiary address
* @return creditsIssued Units of credits (imUSD) issued
*/
function preDeposit(uint256 _underlying, address _beneficiary)
external
returns (uint256 creditsIssued)
{
require(exchangeRate == startingRate, "Can only use this method before streaming begins");
return _deposit(_underlying, _beneficiary, false);
}
/**
* @dev Deposit the senders savings to the vault, and credit them internally with "credits".
* Credit amount is calculated as a ratio of deposit amount and exchange rate:
* credits = underlying / exchangeRate
* We will first update the internal exchange rate by collecting any interest generated on the underlying.
* @param _underlying Units of underlying to deposit into savings vault
* @return creditsIssued Units of credits (imUSD) issued
*/
function depositSavings(uint256 _underlying) external override returns (uint256 creditsIssued) {
return _deposit(_underlying, msg.sender, true);
}
/**
* @dev Deposit the senders savings to the vault, and credit them internally with "credits".
* Credit amount is calculated as a ratio of deposit amount and exchange rate:
* credits = underlying / exchangeRate
* We will first update the internal exchange rate by collecting any interest generated on the underlying.
* @param _underlying Units of underlying to deposit into savings vault
* @param _beneficiary Immediately transfer the imUSD token to this beneficiary address
* @return creditsIssued Units of credits (imUSD) issued
*/
function depositSavings(uint256 _underlying, address _beneficiary)
external
override
returns (uint256 creditsIssued)
{
return _deposit(_underlying, _beneficiary, true);
}
/**
* @dev Overloaded `depositSavings` method with an optional referrer address.
* @param _underlying Units of underlying to deposit into savings vault
* @param _beneficiary Immediately transfer the imUSD token to this beneficiary address
* @param _referrer Referrer address for this deposit
* @return creditsIssued Units of credits (imUSD) issued
*/
function depositSavings(
uint256 _underlying,
address _beneficiary,
address _referrer
) external override returns (uint256 creditsIssued) {
emit Referral(_referrer, _beneficiary, _underlying);
return _deposit(_underlying, _beneficiary, true);
}
/**
* @dev Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD
*/
function _deposit(
uint256 _underlying,
address _beneficiary,
bool _collectInterest
) internal returns (uint256 creditsIssued) {
creditsIssued = _transferAndMint(_underlying, _beneficiary, _collectInterest);
}
/***************************************
REDEEM
****************************************/
// Deprecated in favour of redeemCredits
// Maintaining backwards compatibility, this fn minimics the old redeem fn, in which
// credits are redeemed but the interest from the underlying is not collected.
function redeem(uint256 _credits) external override returns (uint256 massetReturned) {
require(_credits > 0, "Must withdraw something");
(, uint256 payout) = _redeem(_credits, true, true);
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
return payout;
}
/**
* @dev Redeem specific number of the senders "credits" in exchange for underlying.
* Payout amount is calculated as a ratio of credits and exchange rate:
* payout = credits * exchangeRate
* @param _credits Amount of credits to redeem
* @return massetReturned Units of underlying mAsset paid out
*/
function redeemCredits(uint256 _credits) external override returns (uint256 massetReturned) {
require(_credits > 0, "Must withdraw something");
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
(, uint256 payout) = _redeem(_credits, true, true);
return payout;
}
/**
* @dev Redeem credits into a specific amount of underlying.
* Credits needed to burn is calculated using:
* credits = underlying / exchangeRate
* @param _underlying Amount of underlying to redeem
* @return creditsBurned Units of credits burned from sender
*/
function redeemUnderlying(uint256 _underlying)
external
override
returns (uint256 creditsBurned)
{
require(_underlying > 0, "Must withdraw something");
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
// Ensure that the payout was sufficient
(uint256 credits, uint256 massetReturned) = _redeem(_underlying, false, true);
require(massetReturned == _underlying, "Invalid output");
return credits;
}
/**
* @notice Redeem credits into a specific amount of underlying, unwrap
* into a selected output asset, and send to a beneficiary
* Credits needed to burn is calculated using:
* credits = underlying / exchangeRate
* @param _amount Units to redeem (either underlying or credit amount).
* @param _isCreditAmt `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD.
* @param _minAmountOut Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token.
* @param _output Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example:
- bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault.
- bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault.
- bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault.
* @param _beneficiary Address to send `output` tokens to.
* @param _router mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset.
* @param _isBassetOut `true` if `output` is a bAsset. `false` if `output` is a fAsset.
* @return creditsBurned Units of credits burned from sender. eg imUSD or imBTC.
* @return massetReturned Units of the underlying mAssets that were redeemed or swapped for the output tokens. eg mUSD or mBTC.
* @return outputQuantity Units of `output` tokens sent to the beneficiary.
*/
function redeemAndUnwrap(
uint256 _amount,
bool _isCreditAmt,
uint256 _minAmountOut,
address _output,
address _beneficiary,
address _router,
bool _isBassetOut
)
external
override
returns (
uint256 creditsBurned,
uint256 massetReturned,
uint256 outputQuantity
)
{
require(_amount > 0, "Must withdraw something");
require(_output != address(0), "Output address is zero");
require(_beneficiary != address(0), "Beneficiary address is zero");
require(_router != address(0), "Router address is zero");
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
// Ensure that the payout was sufficient
(creditsBurned, massetReturned) = _redeem(_amount, _isCreditAmt, false);
require(
_isCreditAmt ? creditsBurned == _amount : massetReturned == _amount,
"Invalid output"
);
// Approve wrapper to spend contract's underlying; just for this tx
underlying.approve(unwrapper, massetReturned);
// Unwrap the underlying into `output` and transfer to `beneficiary`
outputQuantity = IUnwrapper(unwrapper).unwrapAndSend(
_isBassetOut,
_router,
address(underlying),
_output,
massetReturned,
_minAmountOut,
_beneficiary
);
}
/**
* @dev Internally burn the credits and send the underlying to msg.sender
*/
function _redeem(
uint256 _amt,
bool _isCreditAmt,
bool _transferUnderlying
) internal returns (uint256 creditsBurned, uint256 massetReturned) {
// Centralise credit <> underlying calcs and minimise SLOAD count
uint256 credits_;
uint256 underlying_;
uint256 exchangeRate_;
// If the input is a credit amt, then calculate underlying payout and cache the exchangeRate
if (_isCreditAmt) {
credits_ = _amt;
(underlying_, exchangeRate_) = _creditsToUnderlying(_amt);
}
// If the input is in underlying, then calculate credits needed to burn
else {
underlying_ = _amt;
(credits_, exchangeRate_) = _underlyingToCredits(_amt);
}
_burnTransfer(
underlying_,
credits_,
msg.sender,
msg.sender,
exchangeRate_,
_transferUnderlying
);
emit CreditsRedeemed(msg.sender, credits_, underlying_);
return (credits_, underlying_);
}
struct ConnectorStatus {
// Limit is the max amount of units allowed in the connector
uint256 limit;
// Derived balance of the connector
uint256 inConnector;
}
/**
* @dev Derives the units of collateral held in the connector
* @param _data Struct containing data on balances
* @param _exchangeRate Current system exchange rate
* @return status Contains max amount of assets allowed in connector
*/
function _getConnectorStatus(CachedData memory _data, uint256 _exchangeRate)
internal
pure
returns (ConnectorStatus memory)
{
// Total units of underlying collateralised
uint256 totalCollat = _data.totalCredits.mulTruncate(_exchangeRate);
// Max amount of underlying that can be held in the connector
uint256 limit = totalCollat.mulTruncate(_data.fraction + 2e17);
// Derives amount of underlying present in the connector
uint256 inConnector = _data.rawBalance >= totalCollat ? 0 : totalCollat - _data.rawBalance;
return ConnectorStatus(limit, inConnector);
}
/***************************************
YIELD - E
****************************************/
/** @dev Modifier allowing only the designated poker to execute the fn */
modifier onlyPoker() {
require(msg.sender == poker, "Only poker can execute");
_;
}
/**
* @dev External poke function allows for the redistribution of collateral between here and the
* current connector, setting the ratio back to the defined optimal.
*/
function poke() external onlyPoker {
CachedData memory cachedData = _cacheData();
_poke(cachedData, false);
}
/**
* @dev Governance action to set the address of a new poker
* @param _newPoker Address of the new poker
*/
function setPoker(address _newPoker) external onlyGovernor {
require(_newPoker != address(0) && _newPoker != poker, "Invalid poker");
poker = _newPoker;
emit PokerUpdated(_newPoker);
}
/**
* @dev Governance action to set the percentage of assets that should be held
* in the connector.
* @param _fraction Percentage of assets that should be held there (where 20% == 2e17)
*/
function setFraction(uint256 _fraction) external onlyGovernor {
require(_fraction <= 5e17, "Fraction must be <= 50%");
fraction = _fraction;
CachedData memory cachedData = _cacheData();
_poke(cachedData, true);
emit FractionUpdated(_fraction);
}
/**
* @dev Governance action to set the address of a new connector, and move funds (if any) across.
* @param _newConnector Address of the new connector
*/
function setConnector(address _newConnector) external onlyGovernor {
// Withdraw all from previous by setting target = 0
CachedData memory cachedData = _cacheData();
cachedData.fraction = 0;
_poke(cachedData, true);
// Set new connector
CachedData memory cachedDataNew = _cacheData();
connector = IConnector(_newConnector);
_poke(cachedDataNew, true);
emit ConnectorUpdated(_newConnector);
}
/**
* @dev Governance action to perform an emergency withdraw of the assets in the connector,
* should it be the case that some or all of the liquidity is trapped in. This causes the total
* collateral in the system to go down, causing a hard refresh.
*/
function emergencyWithdraw(uint256 _withdrawAmount) external onlyGovernor {
// withdraw _withdrawAmount from connection
connector.withdraw(_withdrawAmount);
// reset the connector
connector = IConnector(address(0));
emit ConnectorUpdated(address(0));
// set fraction to 0
fraction = 0;
emit FractionUpdated(0);
// check total collateralisation of credits
CachedData memory data = _cacheData();
// use rawBalance as the remaining liquidity in the connector is now written off
_refreshExchangeRate(data.rawBalance, data.totalCredits, true);
emit EmergencyUpdate();
}
/***************************************
YIELD - I
****************************************/
/** @dev Internal poke function to keep the balance between connector and raw balance healthy */
function _poke(CachedData memory _data, bool _ignoreCadence) internal {
require(_data.totalCredits > 0, "Must have something to poke");
// 1. Verify that poke cadence is valid, unless this is a manual action by governance
uint256 currentTime = uint256(block.timestamp);
uint256 timeSinceLastPoke = currentTime - lastPoke;
require(_ignoreCadence || timeSinceLastPoke > POKE_CADENCE, "Not enough time elapsed");
lastPoke = currentTime;
// If there is a connector, check the balance and settle to the specified fraction %
IConnector connector_ = connector;
if (address(connector_) != address(0)) {
// 2. Check and verify new connector balance
uint256 lastBalance_ = lastBalance;
uint256 connectorBalance = connector_.checkBalance();
// Always expect the collateral in the connector to increase in value
require(connectorBalance >= lastBalance_, "Invalid yield");
if (connectorBalance > 0) {
// Validate the collection by ensuring that the APY is not ridiculous
_validateCollection(
connectorBalance,
connectorBalance - lastBalance_,
timeSinceLastPoke
);
}
// 3. Level the assets to Fraction (connector) & 100-fraction (raw)
uint256 sum = _data.rawBalance + connectorBalance;
uint256 ideal = sum.mulTruncate(_data.fraction);
// If there is not enough mAsset in the connector, then deposit
if (ideal > connectorBalance) {
uint256 deposit_ = ideal - connectorBalance;
underlying.approve(address(connector_), deposit_);
connector_.deposit(deposit_);
}
// Else withdraw, if there is too much mAsset in the connector
else if (connectorBalance > ideal) {
// If fraction == 0, then withdraw everything
if (ideal == 0) {
connector_.withdrawAll();
sum = IERC20(underlying).balanceOf(address(this));
} else {
connector_.withdraw(connectorBalance - ideal);
}
}
// Else ideal == connectorBalance (e.g. 0), do nothing
require(connector_.checkBalance() >= ideal, "Enforce system invariant");
// 4i. Refresh exchange rate and emit event
lastBalance = ideal;
_refreshExchangeRate(sum, _data.totalCredits, false);
emit Poked(lastBalance_, ideal, connectorBalance - lastBalance_);
} else {
// 4ii. Refresh exchange rate and emit event
lastBalance = 0;
_refreshExchangeRate(_data.rawBalance, _data.totalCredits, false);
emit PokedRaw();
}
}
/**
* @dev Internal fn to refresh the exchange rate, based on the sum of collateral and the number of credits
* @param _realSum Sum of collateral held by the contract
* @param _totalCredits Total number of credits in the system
* @param _ignoreValidation This is for use in the emergency situation, and ignores a decreasing exchangeRate
*/
function _refreshExchangeRate(
uint256 _realSum,
uint256 _totalCredits,
bool _ignoreValidation
) internal {
// Based on the current exchange rate, how much underlying is collateralised?
(uint256 totalCredited, ) = _creditsToUnderlying(_totalCredits);
// Require the amount of capital held to be greater than the previously credited units
require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase");
// Work out the new exchange rate based on the current capital
uint256 newExchangeRate = _calcExchangeRate(_realSum, _totalCredits);
exchangeRate = newExchangeRate;
emit ExchangeRateUpdated(
newExchangeRate,
_realSum > totalCredited ? _realSum - totalCredited : 0
);
}
/**
* FORKED DIRECTLY FROM SAVINGSMANAGER.sol
* ---------------------------------------
* @dev Validates that an interest collection does not exceed a maximum APY. If last collection
* was under 30 mins ago, simply check it does not exceed 10bps
* @param _newBalance New balance of the underlying
* @param _interest Increase in total supply since last collection
* @param _timeSinceLastCollection Seconds since last collection
*/
function _validateCollection(
uint256 _newBalance,
uint256 _interest,
uint256 _timeSinceLastCollection
) internal pure returns (uint256 extrapolatedAPY) {
// Protect against division by 0
uint256 protectedTime = StableMath.max(1, _timeSinceLastCollection);
uint256 oldSupply = _newBalance - _interest;
uint256 percentageIncrease = _interest.divPrecisely(oldSupply);
uint256 yearsSinceLastCollection = protectedTime.divPrecisely(SECONDS_IN_YEAR);
extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection);
if (protectedTime > 30 minutes) {
require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY");
} else {
require(percentageIncrease < 1e15, "Interest protected from inflating past 10 Bps");
}
}
/***************************************
VIEW - I
****************************************/
struct CachedData {
// SLOAD from 'fraction'
uint256 fraction;
// ERC20 balance of underlying, held by this contract
// underlying.balanceOf(address(this))
uint256 rawBalance;
// totalSupply()
uint256 totalCredits;
}
/**
* @dev Retrieves generic data to avoid duplicate SLOADs
*/
function _cacheData() internal view returns (CachedData memory) {
uint256 balance = underlying.balanceOf(address(this));
return CachedData(fraction, balance, totalSupply());
}
/**
* @dev Converts masset amount into credits based on exchange rate
* c = (masset / exchangeRate) + 1
*/
function _underlyingToCredits(uint256 _underlying)
internal
view
returns (uint256 credits, uint256 exchangeRate_)
{
// e.g. (1e20 * 1e18) / 1e18 = 1e20
// e.g. (1e20 * 1e18) / 14e17 = 7.1429e19
// e.g. 1 * 1e18 / 1e17 + 1 = 11 => 11 * 1e17 / 1e18 = 1.1e18 / 1e18 = 1
exchangeRate_ = exchangeRate;
credits = _underlying.divPrecisely(exchangeRate_) + 1;
}
/**
* @dev Works out a new exchange rate, given an amount of collateral and total credits
* e = underlying / (credits-1)
*/
function _calcExchangeRate(uint256 _totalCollateral, uint256 _totalCredits)
internal
pure
returns (uint256 _exchangeRate)
{
_exchangeRate = _totalCollateral.divPrecisely(_totalCredits - 1);
}
/**
* @dev Converts credit amount into masset based on exchange rate
* m = credits * exchangeRate
*/
function _creditsToUnderlying(uint256 _credits)
internal
view
returns (uint256 underlyingAmount, uint256 exchangeRate_)
{
// e.g. (1e20 * 1e18) / 1e18 = 1e20
// e.g. (1e20 * 14e17) / 1e18 = 1.4e20
exchangeRate_ = exchangeRate;
underlyingAmount = _credits.mulTruncate(exchangeRate_);
}
/*///////////////////////////////////////////////////////////////
IERC4626Vault
//////////////////////////////////////////////////////////////*/
/**
* @notice it must be an ERC-20 token contract. Must not revert.
*
* @return assetTokenAddress the address of the underlying asset token. eg mUSD or mBTC
*/
function asset() external view override returns (address assetTokenAddress) {
return address(underlying);
}
/**
* @return totalManagedAssets the total amount of the underlying asset tokens that is “managed” by Vault.
*/
function totalAssets() external view override returns (uint256 totalManagedAssets) {
return underlying.balanceOf(address(this));
}
/**
* @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.
* @param assets The amount of underlying assets to be convert to vault shares.
* @return shares The amount of vault shares converted from the underlying assets.
*/
function convertToShares(uint256 assets) external view override returns (uint256 shares) {
(shares, ) = _underlyingToCredits(assets);
}
/**
* @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.
* @param shares The amount of vault shares to be converted to the underlying assets.
* @return assets The amount of underlying assets converted from the vault shares.
*/
function convertToAssets(uint256 shares) external view override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
}
/**
* @notice The maximum number of underlying assets that caller can deposit.
* caller Account that the assets will be transferred from.
* @return maxAssets The maximum amount of underlying assets the caller can deposit.
*/
function maxDeposit(
address /** caller **/
) external pure override returns (uint256 maxAssets) {
maxAssets = type(uint256).max;
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be transferred.
* @return shares The amount of vault shares that will be minted.
*/
function previewDeposit(uint256 assets) external view override returns (uint256 shares) {
require(assets > 0, "Must deposit something");
(shares, ) = _underlyingToCredits(assets);
}
/**
* @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.
* Credit amount is calculated as a ratio of deposit amount and exchange rate:
* credits = underlying / exchangeRate
* We will first update the internal exchange rate by collecting any interest generated on the underlying.
* Emits a {Deposit} event.
* @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC
* @param receiver The address to receive the Vault shares.
* @return shares Units of credits issued. eg imUSD or imBTC
*/
function deposit(uint256 assets, address receiver) external override returns (uint256 shares) {
shares = _transferAndMint(assets, receiver, true);
}
/**
*
* @notice Overloaded `deposit` method with an optional referrer address.
* @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC
* @param receiver Address to the new credits will be issued to.
* @param referrer Referrer address for this deposit.
* @return shares Units of credits issued. eg imUSD or imBTC
*/
function deposit(
uint256 assets,
address receiver,
address referrer
) external override returns (uint256 shares) {
shares = _transferAndMint(assets, receiver, true);
emit Referral(referrer, receiver, assets);
}
/**
* @notice The maximum number of vault shares that caller can mint.
* caller Account that the underlying assets will be transferred from.
* @return maxShares The maximum amount of vault shares the caller can mint.
*/
function maxMint(
address /* caller */
) external pure override returns (uint256 maxShares) {
maxShares = type(uint256).max;
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions.
* @param shares The amount of vault shares to be minted.
* @return assets The amount of underlying assests that will be transferred from the caller.
*/
function previewMint(uint256 shares) external view override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
return assets;
}
/**
* @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.
* Emits a {Deposit} event.
*
* @param shares The amount of vault shares to be minted.
* @param receiver The account the vault shares will be minted to.
* @return assets The amount of underlying assets that were transferred from the caller.
*/
function mint(uint256 shares, address receiver) external override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
_transferAndMint(assets, receiver, true);
}
/**
* @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.
* @param shares The amount of vault shares to be minted.
* @param receiver The account the vault shares will be minted to.
* @param referrer Referrer address for this deposit.
* @return assets The amount of underlying assets that were transferred from the caller.
* Emits a {Deposit}, {Referral} events
*/
function mint(
uint256 shares,
address receiver,
address referrer
) external override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
_transferAndMint(assets, receiver, true);
emit Referral(referrer, receiver, assets);
}
/**
* @notice The maximum number of underlying assets that owner can withdraw.
* @param owner Address that owns the underlying assets.
* @return maxAssets The maximum amount of underlying assets the owner can withdraw.
*/
function maxWithdraw(address owner) external view override returns (uint256 maxAssets) {
(maxAssets, ) = _creditsToUnderlying(balanceOf(owner));
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be withdrawn.
* @return shares The amount of vault shares that will be burnt.
*/
function previewWithdraw(uint256 assets) external view override returns (uint256 shares) {
(shares, ) = _underlyingToCredits(assets);
}
/**
* @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.
* Emits a {Withdraw} event.
*
* @param assets The amount of underlying assets to be withdrawn from the vault.
* @param receiver The account that the underlying assets will be transferred to.
* @param owner Account that owns the vault shares to be burnt.
* @return shares The amount of vault shares that were burnt.
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external override returns (uint256 shares) {
require(assets > 0, "Must withdraw something");
uint256 _exchangeRate;
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
(shares, _exchangeRate) = _underlyingToCredits(assets);
_burnTransfer(assets, shares, receiver, owner, _exchangeRate, true);
}
/**
* @notice it must return a limited value if owner is subject to some withdrawal limit or timelock. must return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. MAY be used in the previewRedeem or redeem methods for shares input parameter. must NOT revert.
*
* @param owner Address that owns the shares.
* @return maxShares Total number of shares that owner can redeem.
*/
function maxRedeem(address owner) external view override returns (uint256 maxShares) {
maxShares = balanceOf(owner);
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions.
*
* @return assets the exact amount of underlying assets that would be withdrawn by the caller if redeeming a given exact amount of Vault shares using the redeem method
*/
function previewRedeem(uint256 shares) external view override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
return assets;
}
/**
* @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.
* Emits a {Withdraw} event.
*
* @param shares The amount of vault shares to be burnt.
* @param receiver The account the underlying assets will be transferred to.
* @param owner The account that owns the vault shares to be burnt.
* @return assets The amount of underlying assets that were transferred to the receiver.
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external override returns (uint256 assets) {
require(shares > 0, "Must withdraw something");
uint256 _exchangeRate;
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
(assets, _exchangeRate) = _creditsToUnderlying(shares);
_burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); //transferAssets=true
}
/*///////////////////////////////////////////////////////////////
INTERNAL DEPOSIT/MINT
//////////////////////////////////////////////////////////////*/
function _transferAndMint(
uint256 assets,
address receiver,
bool _collectInterest
) internal returns (uint256 shares) {
require(assets > 0, "Must deposit something");
require(receiver != address(0), "Invalid beneficiary address");
// Collect recent interest generated by basket and update exchange rate
IERC20 mAsset = underlying;
if (_collectInterest) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset));
}
// Transfer tokens from sender to here
require(mAsset.transferFrom(msg.sender, address(this), assets), "Must receive tokens");
// Calc how many credits they receive based on currentRatio
(shares, ) = _underlyingToCredits(assets);
// add credits to ERC20 balances
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
emit SavingsDeposited(receiver, assets, shares);
}
/*///////////////////////////////////////////////////////////////
INTERNAL WITHDRAW/REDEEM
//////////////////////////////////////////////////////////////*/
function _burnTransfer(
uint256 assets,
uint256 shares,
address receiver,
address owner,
uint256 _exchangeRate,
bool transferAssets
) internal {
require(receiver != address(0), "Invalid beneficiary address");
// If caller is not the owner of the shares
uint256 allowed = allowance(owner, msg.sender);
if (msg.sender != owner && allowed != type(uint256).max) {
require(shares <= allowed, "Amount exceeds allowance");
_approve(owner, msg.sender, allowed - shares);
}
// Burn required shares from the owner FIRST
_burn(owner, shares);
// Optionally, transfer tokens from here to receiver
if (transferAssets) {
require(underlying.transfer(receiver, assets), "Must send tokens");
emit Withdraw(msg.sender, receiver, owner, assets, shares);
}
// If this withdrawal pushes the portion of stored collateral in the `connector` over a certain
// threshold (fraction + 20%), then this should trigger a _poke on the connector. This is to avoid
// a situation in which there is a rush on withdrawals for some reason, causing the connector
// balance to go up and thus having too large an exposure.
CachedData memory cachedData = _cacheData();
ConnectorStatus memory status = _getConnectorStatus(cachedData, _exchangeRate);
if (status.inConnector > status.limit) {
_poke(cachedData, false);
}
}
} | Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. assets The amount of underlying assets to be transferred. return shares The amount of vault shares that will be minted./ | function previewDeposit(uint256 assets) external view override returns (uint256 shares) {
require(assets > 0, "Must deposit something");
(shares, ) = _underlyingToCredits(assets);
}
| 11,800,867 |
//Address: 0x3f45d2d5feb6b4b000d2d3b84442eeddf54a735a
//Contract name: LiquidPledging
//Balance: 0 Ether
//Verification Date: 12/20/2017
//Transacion Count: 9
// CODE STARTS HERE
//File: contracts/ILiquidPledgingPlugin.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
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/>.
*/
/// @dev `ILiquidPledgingPlugin` is the basic interface for any
/// liquid pledging plugin
contract ILiquidPledgingPlugin {
/// @notice Plugins are used (much like web hooks) to initiate an action
/// upon any donation, delegation, or transfer; this is an optional feature
/// and allows for extreme customization of the contract. This function
/// implements any action that should be initiated before a transfer.
/// @param pledgeManager The admin or current manager of the pledge
/// @param pledgeFrom This is the Id from which value will be transfered.
/// @param pledgeTo This is the Id that value will be transfered to.
/// @param context The situation that is triggering the plugin:
/// 0 -> Plugin for the owner transferring pledge to another party
/// 1 -> Plugin for the first delegate transferring pledge to another party
/// 2 -> Plugin for the second delegate transferring pledge to another party
/// ...
/// 255 -> Plugin for the intendedProject transferring pledge to another party
///
/// 256 -> Plugin for the owner receiving pledge to another party
/// 257 -> Plugin for the first delegate receiving pledge to another party
/// 258 -> Plugin for the second delegate receiving pledge to another party
/// ...
/// 511 -> Plugin for the intendedProject receiving pledge to another party
/// @param amount The amount of value that will be transfered.
function beforeTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount ) returns (uint maxAllowed);
/// @notice Plugins are used (much like web hooks) to initiate an action
/// upon any donation, delegation, or transfer; this is an optional feature
/// and allows for extreme customization of the contract. This function
/// implements any action that should be initiated after a transfer.
/// @param pledgeManager The admin or current manager of the pledge
/// @param pledgeFrom This is the Id from which value will be transfered.
/// @param pledgeTo This is the Id that value will be transfered to.
/// @param context The situation that is triggering the plugin:
/// 0 -> Plugin for the owner transferring pledge to another party
/// 1 -> Plugin for the first delegate transferring pledge to another party
/// 2 -> Plugin for the second delegate transferring pledge to another party
/// ...
/// 255 -> Plugin for the intendedProject transferring pledge to another party
///
/// 256 -> Plugin for the owner receiving pledge to another party
/// 257 -> Plugin for the first delegate receiving pledge to another party
/// 258 -> Plugin for the second delegate receiving pledge to another party
/// ...
/// 511 -> Plugin for the intendedProject receiving pledge to another party
/// @param amount The amount of value that will be transfered.
function afterTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount
);
}
//File: node_modules/giveth-common-contracts/contracts/Owned.sol
pragma solidity ^0.4.15;
/// @title Owned
/// @author Adrià Massanet <[email protected]>
/// @notice The Owned contract has an owner address, and provides basic
/// authorization control functions, this simplifies & the implementation of
/// user permissions; this contract has three work flows for a change in
/// ownership, the first requires the new owner to validate that they have the
/// ability to accept ownership, the second allows the ownership to be
/// directly transfered without requiring acceptance, and the third allows for
/// the ownership to be removed to allow for decentralization
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
/// @dev The constructor sets the `msg.sender` as the`owner` of the contract
function Owned() public {
owner = msg.sender;
}
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
/// @dev In this 1st option for ownership transfer `proposeOwnership()` must
/// be called first by the current `owner` then `acceptOwnership()` must be
/// called by the `newOwnerCandidate`
/// @notice `onlyOwner` Proposes to transfer control of the contract to a
/// new owner
/// @param _newOwnerCandidate The address being proposed as the new owner
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @notice Can only be called by the `newOwnerCandidate`, accepts the
/// transfer of ownership
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 2nd option for ownership transfer `changeOwnership()` can
/// be called and it will immediately assign ownership to the `newOwner`
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 3rd option for ownership transfer `removeOwnership()` can
/// be called and it will immediately assign ownership to the 0x0 address;
/// it requires a 0xdece be input as a parameter to prevent accidental use
/// @notice Decentralizes the contract, this operation cannot be undone
/// @param _dac `0xdac` has to be entered for this function to work
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
//File: node_modules/giveth-common-contracts/contracts/ERC20.sol
pragma solidity ^0.4.15;
/**
* @title ERC20
* @dev A standard interface for tokens.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20 {
/// @dev Returns the total token supply
function totalSupply() public constant returns (uint256 supply);
/// @dev Returns the account balance of the account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @dev Transfers _value number of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev Transfers _value number of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount
function approve(address _spender, uint256 _value) public returns (bool success);
/// @dev Returns the amount which _spender is still allowed to withdraw from _owner
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);
}
//File: node_modules/giveth-common-contracts/contracts/Escapable.sol
pragma solidity ^0.4.15;
/*
Copyright 2016, Jordi Baylina
Contributor: Adrià Massanet <[email protected]>
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/>.
*/
/// @dev `Escapable` is a base level contract built off of the `Owned`
/// contract; it creates an escape hatch function that can be called in an
/// emergency that will allow designated addresses to send any ether or tokens
/// held in the contract to an `escapeHatchDestination` as long as they were
/// not blacklisted
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist; // Token contract addresses
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
/// @dev The addresses preassigned as `escapeHatchCaller` or `owner`
/// are the only addresses that can call a function with this modifier
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
/// @notice Creates the blacklist of tokens that are not able to be taken
/// out of the contract; can only be done at the deployment, and the logic
/// to add to the blacklist will be in the constructor of a child contract
/// @param _token the token contract address that is to be blacklisted
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
/// @notice Checks to see if `_token` is in the blacklist of tokens
/// @param _token the token address being queried
/// @return False if `_token` is in the blacklist and can't be taken out of
/// the contract via the `escapeHatch()`
function isTokenEscapable(address _token) constant public returns (bool) {
return !escapeBlacklist[_token];
}
/// @notice The `escapeHatch()` should only be called as a last resort if a
/// security issue is uncovered or something unexpected happened
/// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
/// @dev Logic for ether
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
/// @notice Changes the address assigned to call `escapeHatch()`
/// @param _newEscapeHatchCaller The address of a trusted account or
/// contract to call `escapeHatch()` to send the value in this contract to
/// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
//File: contracts/LiquidPledgingBase.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
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/>.
*/
/// @dev This is an interface for `LPVault` which serves as a secure storage for
/// the ETH that backs the Pledges, only after `LiquidPledging` authorizes
/// payments can Pledges be converted for ETH
interface LPVault {
function authorizePayment(bytes32 _ref, address _dest, uint _amount);
function () payable;
}
/// @dev `LiquidPledgingBase` is the base level contract used to carry out
/// liquidPledging's most basic functions, mostly handling and searching the
/// data structures
contract LiquidPledgingBase is Escapable {
// Limits inserted to prevent large loops that could prevent canceling
uint constant MAX_DELEGATES = 10;
uint constant MAX_SUBPROJECT_LEVEL = 20;
uint constant MAX_INTERPROJECT_LEVEL = 20;
enum PledgeAdminType { Giver, Delegate, Project }
enum PledgeState { Pledged, Paying, Paid }
/// @dev This struct defines the details of a `PledgeAdmin` which are
/// commonly referenced by their index in the `admins` array
/// and can own pledges and act as delegates
struct PledgeAdmin {
PledgeAdminType adminType; // Giver, Delegate or Project
address addr; // Account or contract address for admin
string name;
string url; // Can be IPFS hash
uint64 commitTime; // In seconds, used for Givers' & Delegates' vetos
uint64 parentProject; // Only for projects
bool canceled; //Always false except for canceled projects
/// @dev if the plugin is 0x0 then nothing happens, if its an address
// than that smart contract is called when appropriate
ILiquidPledgingPlugin plugin;
}
struct Pledge {
uint amount;
uint64 owner; // PledgeAdmin
uint64[] delegationChain; // List of delegates in order of authority
uint64 intendedProject; // Used when delegates are sending to projects
uint64 commitTime; // When the intendedProject will become the owner
uint64 oldPledge; // Points to the id that this Pledge was derived from
PledgeState pledgeState; // Pledged, Paying, Paid
}
Pledge[] pledges;
PledgeAdmin[] admins; //The list of pledgeAdmins 0 means there is no admin
LPVault public vault;
/// @dev this mapping allows you to search for a specific pledge's
/// index number by the hash of that pledge
mapping (bytes32 => uint64) hPledge2idx;
mapping (bytes32 => bool) pluginWhitelist;
bool public usePluginWhitelist = true;
/////////////
// Modifiers
/////////////
/// @dev The `vault`is the only addresses that can call a function with this
/// modifier
modifier onlyVault() {
require(msg.sender == address(vault));
_;
}
///////////////
// Constructor
///////////////
/// @notice The Constructor creates `LiquidPledgingBase` on the blockchain
/// @param _vault The vault where the ETH backing the pledges is stored
function LiquidPledgingBase(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) Escapable(_escapeHatchCaller, _escapeHatchDestination) public {
admins.length = 1; // we reserve the 0 admin
pledges.length = 1; // we reserve the 0 pledge
vault = LPVault(_vault); // Assigns the specified vault
}
/////////////////////////
// PledgeAdmin functions
/////////////////////////
/// @notice Creates a Giver Admin with the `msg.sender` as the Admin address
/// @param name The name used to identify the Giver
/// @param url The link to the Giver's profile often an IPFS hash
/// @param commitTime The length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
/// @param plugin This is Giver's liquid pledge plugin allowing for
/// extended functionality
/// @return idGiver The id number used to reference this Admin
function addGiver(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idGiver) {
require(isValidPlugin(plugin)); // Plugin check
idGiver = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Giver,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
GiverAdded(idGiver);
}
event GiverAdded(uint64 indexed idGiver);
/// @notice Updates a Giver's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin, and it must be called
/// by the current address of the Giver
/// @param idGiver This is the Admin id number used to specify the Giver
/// @param newAddr The new address that represents this Giver
/// @param newName The new name used to identify the Giver
/// @param newUrl The new link to the Giver's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
function updateGiver(
uint64 idGiver,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage giver = findAdmin(idGiver);
require(giver.adminType == PledgeAdminType.Giver); // Must be a Giver
require(giver.addr == msg.sender); // Current addr had to send this tx
giver.addr = newAddr;
giver.name = newName;
giver.url = newUrl;
giver.commitTime = newCommitTime;
GiverUpdated(idGiver);
}
event GiverUpdated(uint64 indexed idGiver);
/// @notice Creates a Delegate Admin with the `msg.sender` as the Admin addr
/// @param name The name used to identify the Delegate
/// @param url The link to the Delegate's profile often an IPFS hash
/// @param commitTime Sets the length of time in seconds that this delegate
/// can be vetoed. Whenever this delegate is in a delegate chain the time
/// allowed to veto any event must be greater than or equal to this time.
/// @param plugin This is Delegate's liquid pledge plugin allowing for
/// extended functionality
/// @return idxDelegate The id number used to reference this Delegate within
/// the admins array
function addDelegate(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idDelegate) {
require(isValidPlugin(plugin)); // Plugin check
idDelegate = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Delegate,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
DelegateAdded(idDelegate);
}
event DelegateAdded(uint64 indexed idDelegate);
/// @notice Updates a Delegate's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin, and it must be called
/// by the current address of the Delegate
/// @param idDelegate The Admin id number used to specify the Delegate
/// @param newAddr The new address that represents this Delegate
/// @param newName The new name used to identify the Delegate
/// @param newUrl The new link to the Delegate's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds that this
/// delegate can be vetoed. Whenever this delegate is in a delegate chain
/// the time allowed to veto any event must be greater than or equal to
/// this time.
function updateDelegate(
uint64 idDelegate,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime) {
PledgeAdmin storage delegate = findAdmin(idDelegate);
require(delegate.adminType == PledgeAdminType.Delegate);
require(delegate.addr == msg.sender);// Current addr had to send this tx
delegate.addr = newAddr;
delegate.name = newName;
delegate.url = newUrl;
delegate.commitTime = newCommitTime;
DelegateUpdated(idDelegate);
}
event DelegateUpdated(uint64 indexed idDelegate);
/// @notice Creates a Project Admin with the `msg.sender` as the Admin addr
/// @param name The name used to identify the Project
/// @param url The link to the Project's profile often an IPFS hash
/// @param projectAdmin The address for the trusted project manager
/// @param parentProject The Admin id number for the parent project or 0 if
/// there is no parentProject
/// @param commitTime Sets the length of time in seconds the Project has to
/// veto when the Project delegates to another Delegate and they pledge
/// those funds to a project
/// @param plugin This is Project's liquid pledge plugin allowing for
/// extended functionality
/// @return idProject The id number used to reference this Admin
function addProject(
string name,
string url,
address projectAdmin,
uint64 parentProject,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idProject) {
require(isValidPlugin(plugin));
if (parentProject != 0) {
PledgeAdmin storage pa = findAdmin(parentProject);
require(pa.adminType == PledgeAdminType.Project);
require(getProjectLevel(pa) < MAX_SUBPROJECT_LEVEL);
}
idProject = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Project,
projectAdmin,
name,
url,
commitTime,
parentProject,
false,
plugin));
ProjectAdded(idProject);
}
event ProjectAdded(uint64 indexed idProject);
/// @notice Updates a Project's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin or a parentProject,
/// and it must be called by the current address of the Project
/// @param idProject The Admin id number used to specify the Project
/// @param newAddr The new address that represents this Project
/// @param newName The new name used to identify the Project
/// @param newUrl The new link to the Project's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds the Project has
/// to veto when the Project delegates to a Delegate and they pledge those
/// funds to a project
function updateProject(
uint64 idProject,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage project = findAdmin(idProject);
require(project.adminType == PledgeAdminType.Project);
require(project.addr == msg.sender);
project.addr = newAddr;
project.name = newName;
project.url = newUrl;
project.commitTime = newCommitTime;
ProjectUpdated(idProject);
}
event ProjectUpdated(uint64 indexed idAdmin);
//////////
// Public constant functions
//////////
/// @notice A constant getter that returns the total number of pledges
/// @return The total number of Pledges in the system
function numberOfPledges() constant returns (uint) {
return pledges.length - 1;
}
/// @notice A getter that returns the details of the specified pledge
/// @param idPledge the id number of the pledge being queried
/// @return the amount, owner, the number of delegates (but not the actual
/// delegates, the intendedProject (if any), the current commit time and
/// the previous pledge this pledge was derived from
function getPledge(uint64 idPledge) constant returns(
uint amount,
uint64 owner,
uint64 nDelegates,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState pledgeState
) {
Pledge storage p = findPledge(idPledge);
amount = p.amount;
owner = p.owner;
nDelegates = uint64(p.delegationChain.length);
intendedProject = p.intendedProject;
commitTime = p.commitTime;
oldPledge = p.oldPledge;
pledgeState = p.pledgeState;
}
/// @notice Getter to find Delegate w/ the Pledge ID & the Delegate index
/// @param idPledge The id number representing the pledge being queried
/// @param idxDelegate The index number for the delegate in this Pledge
function getPledgeDelegate(uint64 idPledge, uint idxDelegate) constant returns(
uint64 idDelegate,
address addr,
string name
) {
Pledge storage p = findPledge(idPledge);
idDelegate = p.delegationChain[idxDelegate - 1];
PledgeAdmin storage delegate = findAdmin(idDelegate);
addr = delegate.addr;
name = delegate.name;
}
/// @notice A constant getter used to check how many total Admins exist
/// @return The total number of admins (Givers, Delegates and Projects) .
function numberOfPledgeAdmins() constant returns(uint) {
return admins.length - 1;
}
/// @notice A constant getter to check the details of a specified Admin
/// @return addr Account or contract address for admin
/// @return name Name of the pledgeAdmin
/// @return url The link to the Project's profile often an IPFS hash
/// @return commitTime The length of time in seconds the Admin has to veto
/// when the Admin delegates to a Delegate and that Delegate pledges those
/// funds to a project
/// @return parentProject The Admin id number for the parent project or 0
/// if there is no parentProject
/// @return canceled 0 for Delegates & Givers, true if a Project has been
/// canceled
/// @return plugin This is Project's liquidPledging plugin allowing for
/// extended functionality
function getPledgeAdmin(uint64 idAdmin) constant returns (
PledgeAdminType adminType,
address addr,
string name,
string url,
uint64 commitTime,
uint64 parentProject,
bool canceled,
address plugin)
{
PledgeAdmin storage m = findAdmin(idAdmin);
adminType = m.adminType;
addr = m.addr;
name = m.name;
url = m.url;
commitTime = m.commitTime;
parentProject = m.parentProject;
canceled = m.canceled;
plugin = address(m.plugin);
}
////////
// Private methods
///////
/// @notice This creates a Pledge with an initial amount of 0 if one is not
/// created already; otherwise it finds the pledge with the specified
/// attributes; all pledges technically exist, if the pledge hasn't been
/// created in this system yet it simply isn't in the hash array
/// hPledge2idx[] yet
/// @param owner The owner of the pledge being looked up
/// @param delegationChain The list of delegates in order of authority
/// @param intendedProject The project this pledge will Fund after the
/// commitTime has passed
/// @param commitTime The length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
/// @param oldPledge This value is used to store the pledge the current
/// pledge was came from, and in the case a Project is canceled, the Pledge
/// will revert back to it's previous state
/// @param state The pledge state: Pledged, Paying, or state
/// @return The hPledge2idx index number
function findOrCreatePledge(
uint64 owner,
uint64[] delegationChain,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState state
) internal returns (uint64)
{
bytes32 hPledge = sha3(
owner, delegationChain, intendedProject, commitTime, oldPledge, state);
uint64 idx = hPledge2idx[hPledge];
if (idx > 0) return idx;
idx = uint64(pledges.length);
hPledge2idx[hPledge] = idx;
pledges.push(Pledge(
0, owner, delegationChain, intendedProject, commitTime, oldPledge, state));
return idx;
}
/// @notice A getter to look up a Admin's details
/// @param idAdmin The id for the Admin to lookup
/// @return The PledgeAdmin struct for the specified Admin
function findAdmin(uint64 idAdmin) internal returns (PledgeAdmin storage) {
require(idAdmin < admins.length);
return admins[idAdmin];
}
/// @notice A getter to look up a Pledge's details
/// @param idPledge The id for the Pledge to lookup
/// @return The PledgeA struct for the specified Pledge
function findPledge(uint64 idPledge) internal returns (Pledge storage) {
require(idPledge < pledges.length);
return pledges[idPledge];
}
// a constant for when a delegate is requested that is not in the system
uint64 constant NOTFOUND = 0xFFFFFFFFFFFFFFFF;
/// @notice A getter that searches the delegationChain for the level of
/// authority a specific delegate has within a Pledge
/// @param p The Pledge that will be searched
/// @param idDelegate The specified delegate that's searched for
/// @return If the delegate chain contains the delegate with the
/// `admins` array index `idDelegate` this returns that delegates
/// corresponding index in the delegationChain. Otherwise it returns
/// the NOTFOUND constant
function getDelegateIdx(Pledge p, uint64 idDelegate) internal returns(uint64) {
for (uint i=0; i < p.delegationChain.length; i++) {
if (p.delegationChain[i] == idDelegate) return uint64(i);
}
return NOTFOUND;
}
/// @notice A getter to find how many old "parent" pledges a specific Pledge
/// had using a self-referential loop
/// @param p The Pledge being queried
/// @return The number of old "parent" pledges a specific Pledge had
function getPledgeLevel(Pledge p) internal returns(uint) {
if (p.oldPledge == 0) return 0;
Pledge storage oldN = findPledge(p.oldPledge);
return getPledgeLevel(oldN) + 1; // a loop lookup
}
/// @notice A getter to find the longest commitTime out of the owner and all
/// the delegates for a specified pledge
/// @param p The Pledge being queried
/// @return The maximum commitTime out of the owner and all the delegates
function maxCommitTime(Pledge p) internal returns(uint commitTime) {
PledgeAdmin storage m = findAdmin(p.owner);
commitTime = m.commitTime; // start with the owner's commitTime
for (uint i=0; i<p.delegationChain.length; i++) {
m = findAdmin(p.delegationChain[i]);
// If a delegate's commitTime is longer, make it the new commitTime
if (m.commitTime > commitTime) commitTime = m.commitTime;
}
}
/// @notice A getter to find the level of authority a specific Project has
/// using a self-referential loop
/// @param m The Project being queried
/// @return The level of authority a specific Project has
function getProjectLevel(PledgeAdmin m) internal returns(uint) {
assert(m.adminType == PledgeAdminType.Project);
if (m.parentProject == 0) return(1);
PledgeAdmin storage parentNM = findAdmin(m.parentProject);
return getProjectLevel(parentNM) + 1;
}
/// @notice A getter to find if a specified Project has been canceled
/// @param projectId The Admin id number used to specify the Project
/// @return True if the Project has been canceled
function isProjectCanceled(uint64 projectId) constant returns (bool) {
PledgeAdmin storage m = findAdmin(projectId);
if (m.adminType == PledgeAdminType.Giver) return false;
assert(m.adminType == PledgeAdminType.Project);
if (m.canceled) return true;
if (m.parentProject == 0) return false;
return isProjectCanceled(m.parentProject);
}
/// @notice A getter to find the oldest pledge that hasn't been canceled
/// @param idPledge The starting place to lookup the pledges
/// @return The oldest idPledge that hasn't been canceled (DUH!)
function getOldestPledgeNotCanceled(uint64 idPledge
) internal constant returns(uint64) {
if (idPledge == 0) return 0;
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage admin = findAdmin(p.owner);
if (admin.adminType == PledgeAdminType.Giver) return idPledge;
assert(admin.adminType == PledgeAdminType.Project);
if (!isProjectCanceled(p.owner)) return idPledge;
return getOldestPledgeNotCanceled(p.oldPledge);
}
/// @notice A check to see if the msg.sender is the owner or the
/// plugin contract for a specific Admin
/// @param m The Admin being checked
function checkAdminOwner(PledgeAdmin m) internal constant {
require((msg.sender == m.addr) || (msg.sender == address(m.plugin)));
}
///////////////////////////
// Plugin Whitelist Methods
///////////////////////////
function addValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = true;
}
function removeValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = false;
}
function useWhitelist(bool useWhitelist) external onlyOwner {
usePluginWhitelist = useWhitelist;
}
function isValidPlugin(address addr) public returns(bool) {
if (!usePluginWhitelist || addr == 0x0) return true;
bytes32 contractHash = getCodeHash(addr);
return pluginWhitelist[contractHash];
}
function getCodeHash(address addr) public returns(bytes32) {
bytes memory o_code;
assembly {
// retrieve the size of the code, this needs assembly
let size := extcodesize(addr)
// allocate output byte array - this could also be done without assembly
// by using o_code = new bytes(size)
o_code := mload(0x40)
// new "memory end" including padding
mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
// store length in memory
mstore(o_code, size)
// actually retrieve the code, this needs assembly
extcodecopy(addr, add(o_code, 0x20), 0, size)
}
return keccak256(o_code);
}
}
//File: contracts/LiquidPledging.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
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/>.
*/
/// @dev `LiquidPleding` allows for liquid pledging through the use of
/// internal id structures and delegate chaining. All basic operations for
/// handling liquid pledging are supplied as well as plugin features
/// to allow for expanded functionality.
contract LiquidPledging is LiquidPledgingBase {
//////
// Constructor
//////
/// @notice Basic constructor for LiquidPleding, also calls the
/// LiquidPledgingBase contract
/// @dev This constructor also calls the constructor
/// for `LiquidPledgingBase`
/// @param _vault The vault where ETH backing this pledge is stored
function LiquidPledging(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) LiquidPledgingBase(_vault, _escapeHatchCaller, _escapeHatchDestination) {
}
/// @notice This is how value enters the system and how pledges are created;
/// the ether is sent to the vault, an pledge for the Giver is created (or
/// found), the amount of ETH donated in wei is added to the `amount` in
/// the Giver's Pledge, and an LP transfer is done to the idReceiver for
/// the full amount
/// @param idGiver The id of the Giver donating; if 0, a new id is created
/// @param idReceiver The Admin receiving the donation; can be any Admin:
/// the Giver themselves, another Giver, a Delegate or a Project
function donate(uint64 idGiver, uint64 idReceiver) payable {
if (idGiver == 0) {
// default to a 3 day (259200 seconds) commitTime
idGiver = addGiver("", "", 259200, ILiquidPledgingPlugin(0x0));
}
PledgeAdmin storage sender = findAdmin(idGiver);
checkAdminOwner(sender);
require(sender.adminType == PledgeAdminType.Giver);
uint amount = msg.value;
require(amount > 0);
vault.transfer(amount); // Sends the `msg.value` (in wei) to the `vault`
uint64 idPledge = findOrCreatePledge(
idGiver,
new uint64[](0), // Creates empty array for delegationChain
0,
0,
0,
PledgeState.Pledged
);
Pledge storage nTo = findPledge(idPledge);
nTo.amount += amount;
Transfer(0, idPledge, amount); // An event
transfer(idGiver, idPledge, amount, idReceiver); // LP accounting
}
/// @notice Transfers amounts between pledges for internal accounting
/// @param idSender Id of the Admin that is transferring the amount from
/// Pledge to Pledge; this admin must have permissions to move the value
/// @param idPledge Id of the pledge that's moving the value
/// @param amount Quantity of ETH (in wei) that this pledge is transferring
/// the authority to withdraw from the vault
/// @param idReceiver Destination of the `amount`, can be a Giver/Project sending
/// to a Giver, a Delegate or a Project; a Delegate sending to another
/// Delegate, or a Delegate pre-commiting it to a Project
function transfer(
uint64 idSender,
uint64 idPledge,
uint amount,
uint64 idReceiver
){
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage receiver = findAdmin(idReceiver);
PledgeAdmin storage sender = findAdmin(idSender);
checkAdminOwner(sender);
require(p.pledgeState == PledgeState.Pledged);
// If the sender is the owner of the Pledge
if (p.owner == idSender) {
if (receiver.adminType == PledgeAdminType.Giver) {
transferOwnershipToGiver(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Project) {
transferOwnershipToProject(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Delegate) {
uint recieverDIdx = getDelegateIdx(p, idReceiver);
if (p.intendedProject > 0 && recieverDIdx != NOTFOUND) {
// if there is an intendedProject and the receiver is in the delegationChain,
// then we want to preserve the delegationChain as this is a veto of the
// intendedProject by the owner
if (recieverDIdx == p.delegationChain.length - 1) {
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged);
doTransfer(idPledge, toPledge, amount);
} else {
undelegate(idPledge, amount, p.delegationChain.length - receiverDIdx - 1);
}
} else {
// owner is not vetoing an intendedProject and is transferring the pledge to a delegate,
// so we want to reset the delegationChain
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length
);
appendDelegate(idPledge, amount, idReceiver);
}
} else {
// This should never be reached as the reciever.adminType
// should always be either a Giver, Project, or Delegate
assert(false);
}
return;
}
// If the sender is a Delegate
uint senderDIdx = getDelegateIdx(p, idSender);
if (senderDIdx != NOTFOUND) {
// And the receiver is another Giver
if (receiver.adminType == PledgeAdminType.Giver) {
// Only transfer to the Giver who owns the pldege
assert(p.owner == idReceiver);
undelegate(idPledge, amount, p.delegationChain.length);
return;
}
// And the receiver is another Delegate
if (receiver.adminType == PledgeAdminType.Delegate) {
uint receiverDIdx = getDelegateIdx(p, idReceiver);
// And not in the delegationChain
if (receiverDIdx == NOTFOUND) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
// And part of the delegationChain and is after the sender, then
// all of the other delegates after the sender are removed and
// the receiver is appended at the end of the delegationChain
} else if (receiverDIdx > senderDIdx) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
// And is already part of the delegate chain but is before the
// sender, then the sender and all of the other delegates after
// the RECEIVER are removed from the delegationChain
} else if (receiverDIdx <= senderDIdx) {//TODO Check for Game Theory issues (from Arthur) this allows the sender to sort of go komakosi and remove himself and the delegates between himself and the receiver... should this authority be allowed?
undelegate(
idPledge,
amount,
p.delegationChain.length - receiverDIdx - 1
);
}
return;
}
// And the receiver is a Project, all the delegates after the sender
// are removed and the amount is pre-committed to the project
if (receiver.adminType == PledgeAdminType.Project) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
proposeAssignProject(idPledge, amount, idReceiver);
return;
}
}
assert(false); // When the sender is not an owner or a delegate
}
/// @notice Authorizes a payment be made from the `vault` can be used by the
/// Giver to veto a pre-committed donation from a Delegate to an
/// intendedProject
/// @param idPledge Id of the pledge that is to be redeemed into ether
/// @param amount Quantity of ether (in wei) to be authorized
function withdraw(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge); // Updates pledge info
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Pledged);
PledgeAdmin storage owner = findAdmin(p.owner);
checkAdminOwner(owner);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paying
);
doTransfer(idPledge, idNewPledge, amount);
vault.authorizePayment(bytes32(idNewPledge), owner.addr, amount);
}
/// @notice `onlyVault` Confirms a withdraw request changing the PledgeState
/// from Paying to Paid
/// @param idPledge Id of the pledge that is to be withdrawn
/// @param amount Quantity of ether (in wei) to be withdrawn
function confirmPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paid
);
doTransfer(idPledge, idNewPledge, amount);
}
/// @notice `onlyVault` Cancels a withdraw request, changing the PledgeState
/// from Paying back to Pledged
/// @param idPledge Id of the pledge that's withdraw is to be canceled
/// @param amount Quantity of ether (in wei) to be canceled
function cancelPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying); //TODO change to revert????????????????????????????
// When a payment is canceled, never is assigned to a project.
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
oldPledge = normalizePledge(oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
/// @notice Changes the `project.canceled` flag to `true`; cannot be undone
/// @param idProject Id of the project that is to be canceled
function cancelProject(uint64 idProject) {
PledgeAdmin storage project = findAdmin(idProject);
checkAdminOwner(project);
project.canceled = true;
CancelProject(idProject);
}
/// @notice Transfers `amount` in `idPledge` back to the `oldPledge` that
/// that sent it there in the first place, a Ctrl-z
/// @param idPledge Id of the pledge that is to be canceled
/// @param amount Quantity of ether (in wei) to be transfered to the
/// `oldPledge`
function cancelPledge(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
require(p.oldPledge != 0);
PledgeAdmin storage m = findAdmin(p.owner);
checkAdminOwner(m);
uint64 oldPledge = getOldestPledgeNotCanceled(p.oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
////////
// Multi pledge methods
////////
// @dev This set of functions makes moving a lot of pledges around much more
// efficient (saves gas) than calling these functions in series
/// @dev Bitmask used for dividing pledge amounts in Multi pledge methods
uint constant D64 = 0x10000000000000000;
/// @notice Transfers multiple amounts within multiple Pledges in an
/// efficient single call
/// @param idSender Id of the Admin that is transferring the amounts from
/// all the Pledges; this admin must have permissions to move the value
/// @param pledgesAmounts An array of Pledge amounts and the idPledges with
/// which the amounts are associated; these are extrapolated using the D64
/// bitmask
/// @param idReceiver Destination of the `pledesAmounts`, can be a Giver or
/// Project sending to a Giver, a Delegate or a Project; a Delegate sending
/// to another Delegate, or a Delegate pre-commiting it to a Project
function mTransfer(
uint64 idSender,
uint[] pledgesAmounts,
uint64 idReceiver
) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
transfer(idSender, idPledge, amount, idReceiver);
}
}
/// @notice Authorizes multiple amounts within multiple Pledges to be
/// withdrawn from the `vault` in an efficient single call
/// @param pledgesAmounts An array of Pledge amounts and the idPledges with
/// which the amounts are associated; these are extrapolated using the D64
/// bitmask
function mWithdraw(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
withdraw(idPledge, amount);
}
}
/// @notice `mConfirmPayment` allows for multiple pledges to be confirmed
/// efficiently
/// @param pledgesAmounts An array of pledge amounts and IDs which are extrapolated
/// using the D64 bitmask
function mConfirmPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
confirmPayment(idPledge, amount);
}
}
/// @notice `mCancelPayment` allows for multiple pledges to be canceled
/// efficiently
/// @param pledgesAmounts An array of pledge amounts and IDs which are extrapolated
/// using the D64 bitmask
function mCancelPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
cancelPayment(idPledge, amount);
}
}
/// @notice `mNormalizePledge` allows for multiple pledges to be
/// normalized efficiently
/// @param pledges An array of pledge IDs
function mNormalizePledge(uint64[] pledges) {
for (uint i = 0; i < pledges.length; i++ ) {
normalizePledge( pledges[i] );
}
}
////////
// Private methods
///////
/// @notice `transferOwnershipToProject` allows for the transfer of
/// ownership to the project, but it can also be called by a project
/// to un-delegate everyone by setting one's own id for the idReceiver
/// @param idPledge Id of the pledge to be transfered.
/// @param amount Quantity of value that's being transfered
/// @param idReceiver The new owner of the project (or self to un-delegate)
function transferOwnershipToProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
// Ensure that the pledge is not already at max pledge depth
// and the project has not been canceled
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
idReceiver, // Set the new owner
new uint64[](0), // clear the delegation chain
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `transferOwnershipToGiver` allows for the transfer of
/// value back to the Giver, value is placed in a pledged state
/// without being attached to a project, delegation chain, or time line.
/// @param idPledge Id of the pledge to be transfered.
/// @param amount Quantity of value that's being transfered
/// @param idReceiver The new owner of the pledge
function transferOwnershipToGiver(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
uint64 toPledge = findOrCreatePledge(
idReceiver,
new uint64[](0),
0,
0,
0,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `appendDelegate` allows for a delegate to be added onto the
/// end of the delegate chain for a given Pledge.
/// @param idPledge Id of the pledge thats delegate chain will be modified.
/// @param amount Quantity of value that's being chained.
/// @param idReceiver The delegate to be added at the end of the chain
function appendDelegate(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(p.delegationChain.length < MAX_DELEGATES);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length + 1
);
for (uint i = 0; i<p.delegationChain.length; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
// Make the last item in the array the idReceiver
newDelegationChain[p.delegationChain.length] = idReceiver;
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `appendDelegate` allows for a delegate to be added onto the
/// end of the delegate chain for a given Pledge.
/// @param idPledge Id of the pledge thats delegate chain will be modified.
/// @param amount Quantity of value that's shifted from delegates.
/// @param q Number (or depth) of delegates to remove
/// @return toPledge The id for the pledge being adjusted or created
function undelegate(
uint64 idPledge,
uint amount,
uint q
) internal returns (uint64)
{
Pledge storage p = findPledge(idPledge);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length - q
);
for (uint i=0; i<p.delegationChain.length - q; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
return toPledge;
}
/// @notice `proposeAssignProject` proposes the assignment of a pledge
/// to a specific project.
/// @dev This function should potentially be named more specifically.
/// @param idPledge Id of the pledge that will be assigned.
/// @param amount Quantity of value this pledge leader would be assigned.
/// @param idReceiver The project this pledge will potentially
/// be assigned to.
function proposeAssignProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
idReceiver,
uint64(getTime() + maxCommitTime(p)),
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `doTransfer` is designed to allow for pledge amounts to be
/// shifted around internally.
/// @param from This is the Id from which value will be transfered.
/// @param to This is the Id that value will be transfered to.
/// @param _amount The amount of value that will be transfered.
function doTransfer(uint64 from, uint64 to, uint _amount) internal {
uint amount = callPlugins(true, from, to, _amount);
if (from == to) {
return;
}
if (amount == 0) {
return;
}
Pledge storage nFrom = findPledge(from);
Pledge storage nTo = findPledge(to);
require(nFrom.amount >= amount);
nFrom.amount -= amount;
nTo.amount += amount;
Transfer(from, to, amount);
callPlugins(false, from, to, amount);
}
/// @notice Only affects pledges with the Pledged PledgeState for 2 things:
/// #1: Checks if the pledge should be committed. This means that
/// if the pledge has an intendedProject and it is past the
/// commitTime, it changes the owner to be the proposed project
/// (The UI will have to read the commit time and manually do what
/// this function does to the pledge for the end user
/// at the expiration of the commitTime)
///
/// #2: Checks to make sure that if there has been a cancellation in the
/// chain of projects, the pledge's owner has been changed
/// appropriately.
///
/// This function can be called by anybody at anytime on any pledge.
/// In general it can be called to force the calls of the affected
/// plugins, which also need to be predicted by the UI
/// @param idPledge This is the id of the pledge that will be normalized
/// @return The normalized Pledge!
function normalizePledge(uint64 idPledge) returns(uint64) {
Pledge storage p = findPledge(idPledge);
// Check to make sure this pledge hasn't already been used
// or is in the process of being used
if (p.pledgeState != PledgeState.Pledged) {
return idPledge;
}
// First send to a project if it's proposed and committed
if ((p.intendedProject > 0) && ( getTime() > p.commitTime)) {
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
p.intendedProject,
new uint64[](0),
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, p.amount);
idPledge = toPledge;
p = findPledge(idPledge);
}
toPledge = getOldestPledgeNotCanceled(idPledge);
if (toPledge != idPledge) {
doTransfer(idPledge, toPledge, p.amount);
}
return toPledge;
}
/////////////
// Plugins
/////////////
/// @notice `callPlugin` is used to trigger the general functions in the
/// plugin for any actions needed before and after a transfer happens.
/// Specifically what this does in relation to the plugin is something
/// that largely depends on the functions of that plugin. This function
/// is generally called in pairs, once before, and once after a transfer.
/// @param before This toggle determines whether the plugin call is occurring
/// before or after a transfer.
/// @param adminId This should be the Id of the *trusted* individual
/// who has control over this plugin.
/// @param fromPledge This is the Id from which value is being transfered.
/// @param toPledge This is the Id that value is being transfered to.
/// @param context The situation that is triggering the plugin. See plugin
/// for a full description of contexts.
/// @param amount The amount of value that is being transfered.
function callPlugin(
bool before,
uint64 adminId,
uint64 fromPledge,
uint64 toPledge,
uint64 context,
uint amount
) internal returns (uint allowedAmount) {
uint newAmount;
allowedAmount = amount;
PledgeAdmin storage admin = findAdmin(adminId);
// Checks admin has a plugin assigned and a non-zero amount is requested
if ((address(admin.plugin) != 0) && (allowedAmount > 0)) {
// There are two seperate functions called in the plugin.
// One is called before the transfer and one after
if (before) {
newAmount = admin.plugin.beforeTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
require(newAmount <= allowedAmount);
allowedAmount = newAmount;
} else {
admin.plugin.afterTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
}
}
}
/// @notice `callPluginsPledge` is used to apply plugin calls to
/// the delegate chain and the intended project if there is one.
/// It does so in either a transferring or receiving context based
/// on the `idPledge` and `fromPledge` parameters.
/// @param before This toggle determines whether the plugin call is occuring
/// before or after a transfer.
/// @param idPledge This is the Id of the pledge on which this plugin
/// is being called.
/// @param fromPledge This is the Id from which value is being transfered.
/// @param toPledge This is the Id that value is being transfered to.
/// @param amount The amount of value that is being transfered.
function callPluginsPledge(
bool before,
uint64 idPledge,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
// Determine if callPlugin is being applied in a receiving
// or transferring context
uint64 offset = idPledge == fromPledge ? 0 : 256;
allowedAmount = amount;
Pledge storage p = findPledge(idPledge);
// Always call the plugin on the owner
allowedAmount = callPlugin(
before,
p.owner,
fromPledge,
toPledge,
offset,
allowedAmount
);
// Apply call plugin to all delegates
for (uint64 i=0; i<p.delegationChain.length; i++) {
allowedAmount = callPlugin(
before,
p.delegationChain[i],
fromPledge,
toPledge,
offset + i+1,
allowedAmount
);
}
// If there is an intended project also call the plugin in
// either a transferring or receiving context based on offset
// on the intended project
if (p.intendedProject > 0) {
allowedAmount = callPlugin(
before,
p.intendedProject,
fromPledge,
toPledge,
offset + 255,
allowedAmount
);
}
}
/// @notice `callPlugins` calls `callPluginsPledge` once for the transfer
/// context and once for the receiving context. The aggregated
/// allowed amount is then returned.
/// @param before This toggle determines whether the plugin call is occurring
/// before or after a transfer.
/// @param fromPledge This is the Id from which value is being transferred.
/// @param toPledge This is the Id that value is being transferred to.
/// @param amount The amount of value that is being transferred.
function callPlugins(
bool before,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
allowedAmount = amount;
// Call the pledges plugins in the transfer context
allowedAmount = callPluginsPledge(
before,
fromPledge,
fromPledge,
toPledge,
allowedAmount
);
// Call the pledges plugins in the receive context
allowedAmount = callPluginsPledge(
before,
toPledge,
fromPledge,
toPledge,
allowedAmount
);
}
/////////////
// Test functions
/////////////
/// @notice Basic helper function to return the current time
function getTime() internal returns (uint) {
return now;
}
// Event Delcerations
event Transfer(uint64 indexed from, uint64 indexed to, uint amount);
event CancelProject(uint64 indexed idProject);
}
| `doTransfer` is designed to allow for pledge amounts to be shifted around internally. from This is the Id from which value will be transfered. to This is the Id that value will be transfered to. _amount The amount of value that will be transfered. | function doTransfer(uint64 from, uint64 to, uint _amount) internal {
uint amount = callPlugins(true, from, to, _amount);
if (from == to) {
return;
}
if (amount == 0) {
return;
}
Pledge storage nFrom = findPledge(from);
Pledge storage nTo = findPledge(to);
require(nFrom.amount >= amount);
nFrom.amount -= amount;
nTo.amount += amount;
Transfer(from, to, amount);
callPlugins(false, from, to, amount);
}
| 12,923,224 |
pragma solidity ^0.4.23;
/**
* @title ECCMath
*
* Functions for working with integers, curve-points, etc.
*
* @author Andreas Olofsson ([email protected]). Reworked by Alexander Vlasov ([email protected])
*/
library ECCMath {
/// @dev Modular inverse of a (mod p) using euclid.
/// 'a' and 'p' must be co-prime.
/// @param a The number.
/// @param p The mmodulus.
/// @return x such that ax = 1 (mod p)
function invmod(uint a, uint p) internal pure returns (uint) {
if (a == 0 || a == p || p == 0)
return 0;
if (a > p)
a = a % p;
int t1;
int t2 = 1;
uint r1 = p;
uint r2 = a;
uint q;
while (r2 != 0) {
q = r1 / r2;
(t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2);
}
if (t1 < 0)
return (p - uint(-t1));
return uint(t1);
}
/// @dev Modular exponentiation, b^e % m
/// Uses precompile for computation
/// @param b The base.
/// @param e The exponent.
/// @param m The modulus.
/// @return x such that x = b**e (mod m)
function expmod(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
uint256[6] memory input;
uint256[1] memory output;
input[0] = 0x20; // length_of_BASE
input[1] = 0x20; // length_of_EXPONENT
input[2] = 0x20; // length_of_MODULUS
input[3] = b;
input[4] = e;
input[5] = m;
assembly {
if iszero(staticcall(not(0), 5, input, 0xc0, output, 0x20)) {
revert(0, 0)
}
}
return output[0];
}
/// @dev Converts a point (Px, Py, Pz) expressed in Jacobian coordinates to (Px', Py', 1).
/// Mutates P.
/// @param P The point.
/// @param zInv The modular inverse of 'Pz'.
/// @param z2Inv The square of zInv
/// @param prime The prime modulus.
/// @return (Px', Py', 1)
function toZ1(uint[3] memory P, uint zInv, uint z2Inv, uint prime) internal pure {
P[0] = mulmod(P[0], z2Inv, prime);
P[1] = mulmod(P[1], mulmod(zInv, z2Inv, prime), prime);
P[2] = 1;
}
/// @dev See _toZ1(uint[3], uint, uint).
/// Warning: Computes a modular inverse.
/// @param PJ The point.
/// @param prime The prime modulus.
/// @return (Px', Py', 1)
function toZ1(uint[3] PJ, uint prime) internal pure {
uint zInv = invmod(PJ[2], prime);
uint zInv2 = mulmod(zInv, zInv, prime);
PJ[0] = mulmod(PJ[0], zInv2, prime);
PJ[1] = mulmod(PJ[1], mulmod(zInv, zInv2, prime), prime);
PJ[2] = 1;
}
} | See _toZ1(uint[3], uint, uint). Warning: Computes a modular inverse. PJ The point. prime The prime modulus. return (Px', Py', 1) | function toZ1(uint[3] PJ, uint prime) internal pure {
uint zInv = invmod(PJ[2], prime);
uint zInv2 = mulmod(zInv, zInv, prime);
PJ[0] = mulmod(PJ[0], zInv2, prime);
PJ[1] = mulmod(PJ[1], mulmod(zInv, zInv2, prime), prime);
PJ[2] = 1;
}
| 12,657,295 |
pragma solidity ^0.5.12;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../../interfaces/curve/ICurveModule.sol";
import "../../interfaces/curve/IFundsModule.sol";
import "../../interfaces/curve/ILoanModule.sol";
import "../../interfaces/curve/ILoanProposalsModule.sol";
import "../../interfaces/token/IPToken.sol";
import "../../common/Module.sol";
import "./FundsOperatorRole.sol";
//solhint-disable func-order
contract FundsModule is Module, IFundsModule, FundsOperatorRole {
using SafeMath for uint256;
uint256 private constant STATUS_PRICE_AMOUNT = 10**18; // Used to calculate price for Status event, should represent 1 DAI
uint256 public lBalance; //Tracked balance of liquid token, may be less or equal to lToken.balanceOf(address(this))
mapping(address=>uint256) pBalances; //Stores how many pTokens is locked in FundsModule by user
function initialize(address _pool) public initializer {
Module.initialize(_pool);
FundsOperatorRole.initialize(_msgSender());
//lBalance = lToken.balanceOf(address(this)); //We do not initialize lBalance to preserve it's previous value when updgrade
}
/**
* @notice Deposit liquid tokens to the pool
* @param from Address of the user, who sends tokens. Should have enough allowance.
* @param amount Amount of tokens to deposit
*/
function depositLTokens(address from, uint256 amount) public onlyFundsOperator {
lBalance = lBalance.add(amount);
require(lToken().transferFrom(from, address(this), amount), "FundsModule: deposit failed");
emitStatus();
}
/**
* @notice Withdraw liquid tokens from the pool
* @param to Address of the user, who sends tokens. Should have enough allowance.
* @param amount Amount of tokens to deposit
*/
function withdrawLTokens(address to, uint256 amount) public onlyFundsOperator {
withdrawLTokens(to, amount, 0);
}
/**
* @notice Withdraw liquid tokens from the pool
* @param to Address of the user, who sends tokens. Should have enough allowance.
* @param amount Amount of tokens to deposit
* @param poolFee Pool fee will be sent to pool owner
*/
function withdrawLTokens(address to, uint256 amount, uint256 poolFee) public onlyFundsOperator {
lBalance = lBalance.sub(amount);
if (amount > 0) { //This will be false for "fee only" withdrawal in LiquidityModule.withdrawForRepay()
require(lToken().transfer(to, amount), "FundsModule: withdraw failed");
}
if (poolFee > 0) {
lBalance = lBalance.sub(poolFee);
require(lToken().transfer(owner(), poolFee), "FundsModule: fee transfer failed");
}
emitStatus();
}
/**
* @notice Deposit pool tokens to the pool
* @param from Address of the user, who sends tokens. Should have enough allowance.
* @param amount Amount of tokens to deposit
*/
function depositPTokens(address from, uint256 amount) public onlyFundsOperator {
require(pToken().transferFrom(from, address(this), amount), "FundsModule: deposit failed"); //this also runs claimDistributions(from)
pBalances[from] = pBalances[from].add(amount);
}
/**
* @notice Withdraw pool tokens from the pool
* @param to Address of the user, who receivs tokens.
* @param amount Amount of tokens to deposit
*/
function withdrawPTokens(address to, uint256 amount) public onlyFundsOperator {
require(pToken().transfer(to, amount), "FundsModule: withdraw failed"); //this also runs claimDistributions(to)
pBalances[to] = pBalances[to].sub(amount);
}
/**
* @notice Mint new PTokens
* @param to Address of the user, who sends tokens.
* @param amount Amount of tokens to mint
*/
function mintPTokens(address to, uint256 amount) public onlyFundsOperator {
assert(to != address(this)); //Use mintAndLockPTokens
require(pToken().mint(to, amount), "FundsModule: mint failed");
}
function distributePTokens(uint256 amount) public onlyFundsOperator {
pToken().distribute(amount); // This call will eventually mint new pTokens (with next distribution, which should be once a day)
}
/**
* @notice Burn pool tokens
* @param from Address of the user, whos tokens we burning. Should have enough allowance.
* @param amount Amount of tokens to burn
*/
function burnPTokens(address from, uint256 amount) public onlyFundsOperator {
assert(from != address(this)); //Use burnLockedPTokens
pToken().burnFrom(from, amount); // This call will revert if sender has not enough pTokens. Allowance is always unlimited for FundsModule
}
/**
* @notice Lock pTokens for a loan
* @param from list of addresses to lock tokens from
* @param amount list of amounts addresses to lock tokens from
*/
function lockPTokens(address[] calldata from, uint256[] calldata amount) external onlyFundsOperator {
require(from.length == amount.length, "FundsModule: from and amount length should match");
//pToken().claimDistributions(address(this));
pToken().claimDistributions(from);
uint256 lockAmount;
for (uint256 i=0; i < from.length; i++) {
address account = from[i];
pBalances[account] = pBalances[account].sub(amount[i]);
lockAmount = lockAmount.add(amount[i]);
}
pBalances[address(this)] = pBalances[address(this)].add(lockAmount);
}
function mintAndLockPTokens(uint256 amount) public onlyFundsOperator {
require(pToken().mint(address(this), amount), "FundsModule: mint failed");
pBalances[address(this)] = pBalances[address(this)].add(amount);
}
function unlockAndWithdrawPTokens(address to, uint256 amount) public onlyFundsOperator {
require(pToken().transfer(to, amount), "FundsModule: withdraw failed"); //this also runs claimDistributions(to)
pBalances[address(this)] = pBalances[address(this)].sub(amount);
}
function burnLockedPTokens(uint256 amount) public onlyFundsOperator {
pToken().burn(amount); //This call will revert if something goes wrong
pBalances[address(this)] = pBalances[address(this)].sub(amount);
}
/**
* @notice Refund liquid tokens accidentially sent directly to this contract
* @param to Address of the user, who receives refund
* @param amount Amount of tokens to send
*/
function refundLTokens(address to, uint256 amount) public onlyFundsOperator {
uint256 realLBalance = lToken().balanceOf(address(this));
require(realLBalance.sub(amount) >= lBalance, "FundsModule: not enough tokens to refund");
require(lToken().transfer(to, amount), "FundsModule: refund failed");
}
/**
* @return Amount of pTokens locked in FundsModule by account
*/
function pBalanceOf(address account) public view returns(uint256){
return pBalances[account];
}
/**
* @notice Calculates how many pTokens should be given to user for increasing liquidity
* @param lAmount Amount of liquid tokens which will be put into the pool
* @return Amount of pToken which should be sent to sender
*/
function calculatePoolEnter(uint256 lAmount) public view returns(uint256) {
uint256 lDebts = loanModule().totalLDebts();
return curveModule().calculateEnter(lBalance, lDebts, lAmount);
}
/**
* @notice Calculates how many pTokens should be given to user for increasing liquidity
* @param lAmount Amount of liquid tokens which will be put into the pool
* @param liquidityCorrection Amount of liquid tokens to remove from liquidity because it was "virtually" withdrawn
* @return Amount of pToken which should be sent to sender
*/
function calculatePoolEnter(uint256 lAmount, uint256 liquidityCorrection) public view returns(uint256) {
uint256 lDebts = loanModule().totalLDebts();
return curveModule().calculateEnter(lBalance.sub(liquidityCorrection), lDebts, lAmount);
}
/**
* @notice Calculates how many pTokens should be taken from user for decreasing liquidity
* @param lAmount Amount of liquid tokens which will be removed from the pool
* @return Amount of pToken which should be taken from sender
*/
function calculatePoolExit(uint256 lAmount) public view returns(uint256) {
uint256 lProposals = loanProposalsModule().totalLProposals();
return curveModule().calculateExit(lBalance.sub(lProposals), lAmount);
}
/**
* @notice Calculates amount of pTokens which should be burned/locked when liquidity removed from pool
* @param lAmount Amount of liquid tokens beeing withdrawn. Does NOT include part for pool
* @return Amount of pTokens to burn/lock
*/
function calculatePoolExitWithFee(uint256 lAmount) public view returns(uint256) {
uint256 lProposals = loanProposalsModule().totalLProposals();
return curveModule().calculateExitWithFee(lBalance.sub(lProposals), lAmount);
}
/**
* @notice Calculates amount of pTokens which should be burned/locked when liquidity removed from pool
* @param lAmount Amount of liquid tokens beeing withdrawn. Does NOT include part for pool
* @param liquidityCorrection Amount of liquid tokens to remove from liquidity because it was "virtually" withdrawn
* @return Amount of pTokens to burn/lock
*/
function calculatePoolExitWithFee(uint256 lAmount, uint256 liquidityCorrection) public view returns(uint256) {
uint256 lProposals = loanProposalsModule().totalLProposals();
return curveModule().calculateExitWithFee(lBalance.sub(liquidityCorrection).sub(lProposals), lAmount);
}
/**
* @notice Calculates how many liquid tokens should be removed from pool when decreasing liquidity
* @param pAmount Amount of pToken which should be taken from sender
* @return Amount of liquid tokens which will be removed from the pool: total, part for sender, part for pool
*/
function calculatePoolExitInverse(uint256 pAmount) public view returns(uint256, uint256, uint256) {
uint256 lProposals = loanProposalsModule().totalLProposals();
return curveModule().calculateExitInverseWithFee(lBalance.sub(lProposals), pAmount);
}
function emitStatus() private {
uint256 lDebts = loanModule().totalLDebts();
uint256 lProposals = loanProposalsModule().totalLProposals();
uint256 pEnterPrice = curveModule().calculateEnter(lBalance, lDebts, STATUS_PRICE_AMOUNT);
uint256 pExitPrice; // = 0; //0 is default value
if (lBalance >= STATUS_PRICE_AMOUNT) {
pExitPrice = curveModule().calculateExit(lBalance.sub(lProposals), STATUS_PRICE_AMOUNT);
} else {
pExitPrice = 0;
}
emit Status(lBalance, lDebts, lProposals, pEnterPrice, pExitPrice);
}
function curveModule() private view returns(ICurveModule) {
return ICurveModule(getModuleAddress(MODULE_CURVE));
}
function loanModule() private view returns(ILoanModule) {
return ILoanModule(getModuleAddress(MODULE_LOAN));
}
function loanProposalsModule() private view returns(ILoanProposalsModule) {
return ILoanProposalsModule(getModuleAddress(MODULE_LOAN_PROPOSALS));
}
function pToken() private view returns(IPToken){
return IPToken(getModuleAddress(MODULE_PTOKEN));
}
function lToken() private view returns(IERC20){
return IERC20(getModuleAddress(MODULE_LTOKEN));
}
} | Withdraw liquid tokens from the pool to Address of the user, who sends tokens. Should have enough allowance. amount Amount of tokens to deposit/ | function withdrawLTokens(address to, uint256 amount) public onlyFundsOperator {
withdrawLTokens(to, amount, 0);
}
| 2,487,198 |
./full_match/1/0x5d91247F49e5f9eb05b948d638616f071d2abf00/sources/browser/TheRushV1.sol | To stake token user will call this method user can stake only once whilestakedAmount[msg.sender] = amount use this for tokens other than SURG (does not support burn-on-transfer tokens)stakedAmount[msg.sender] = safeAdd(stakedAmount[msg.sender], amount); Subtracting slash amount only when staking SURG | function stake(uint256 amount) external returns (bool) {
require(enabled == true);
require(amount <= 115792089237316195423570985008687907853269984665640564039457584007913129639935, "Overflow");
if (stakedAmount[msg.sender] == 0) {
bool isOk = IERC20(StakingToken).transferFrom(msg.sender,address(this),amount);
require(isOk, "TOKEN_TRANSFER_FAIL");
emit Staked(msg.sender, amount);
lastStack[msg.sender] = block.timestamp;
return true;
}
else {
bool isOk = IERC20(StakingToken).transferFrom(msg.sender,address(this),amount);
require(isOk, "TOKEN_TRANSFER_FAIL");
emit Staked(msg.sender, amount);
lastStack[msg.sender] = block.timestamp;
return true;
}
}
| 9,818,662 |
pragma solidity ^0.4.17;
contract MyToken {
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
string public name;
string public symbol;
uint8 public decimals;
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
}
function transfer(address _to, uint256 _value) public {
/* Check if sender has balance and for overflows */
require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]);
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
} | This creates an array with all balances / Initializes contract with initial supply tokens to the creator of the contract / | function MyToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public {
}
| 2,226,631 |
// SPDX-License-Identifier: MIT
// AaveWalletManager.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. 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 "@openzeppelin/contracts/math/SafeMath.sol";
import "../../lib/WalletManagerBase.sol";
import "../../interfaces/IChargedSettings.sol";
import "./AaveSmartWalletB.sol";
/**
* @notice Wallet Manager for Aave
* @dev Non-upgradeable Contract
*/
contract AaveWalletManagerB is WalletManagerBase {
using SafeMath for uint256;
event AaveBridgeSet(address indexed aaveBridge);
event ChargedSettingsSet(address indexed settings);
event ValidRewardsTokenSet(address indexed rewardsToken, bool state);
IChargedSettings internal _chargedSettings;
address internal _aaveBridge;
uint256 internal _referralCode;
mapping (address => bool) public _rewardsTokenWhitelist;
/***********************************|
| Initialization |
|__________________________________*/
constructor () public {
_walletTemplate = address(new AaveSmartWalletB());
}
/***********************************|
| Public |
|__________________________________*/
function isReserveActive(address contractAddress, uint256 tokenId, address assetToken) external view override returns (bool) {
uint256 uuid = contractAddress.getTokenUUID(tokenId);
if (_wallets[uuid] == address(0x0)) { return false; }
return AaveSmartWalletB(_wallets[uuid]).isReserveActive(assetToken);
}
function getReserveInterestToken(address contractAddress, uint256 tokenId, address assetToken) external view override returns (address) {
uint256 uuid = contractAddress.getTokenUUID(tokenId);
if (_wallets[uuid] == address(0x0)) { return address(0x0); }
return AaveSmartWalletB(_wallets[uuid]).getReserveInterestToken(assetToken);
}
/**
* @notice Gets the Principal-Amount of Assets held in the Smart-Wallet
* @param contractAddress The Address to the External Contract of the Token
* @param tokenId The ID of the Token within the External Contract
* @return The Principal-Balance of the Smart-Wallet
*/
function getPrincipal(address contractAddress, uint256 tokenId, address assetToken) external override returns (uint256) {
uint256 uuid = contractAddress.getTokenUUID(tokenId);
if (_wallets[uuid] == address(0x0)) { return 0; }
return AaveSmartWalletB(_wallets[uuid]).getPrincipal(assetToken);
}
/**
* @notice Gets the Interest-Amount that the Token has generated
* @param contractAddress The Address to the External Contract of the Token
* @param tokenId The ID of the Token within the External Contract
* @return creatorInterest The NFT Creator's portion of the Interest
* @return ownerInterest The NFT Owner's portion of the Interest
*/
function getInterest(address contractAddress, uint256 tokenId, address assetToken)
external
override
returns (uint256 creatorInterest, uint256 ownerInterest)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
if (_wallets[uuid] != address(0x0)) {
(, uint256 annuityPct) = _chargedSettings.getCreatorAnnuities(contractAddress, tokenId);
return AaveSmartWalletB(_wallets[uuid]).getInterest(assetToken, annuityPct);
}
}
/**
* @notice Gets the Available Balance of Assets held in the Token
* @param contractAddress The Address to the External Contract of the Token
* @param tokenId The ID of the Token within the External Contract
* @return The Available Balance of the Token
*/
function getTotal(address contractAddress, uint256 tokenId, address assetToken) external override returns (uint256) {
uint256 uuid = contractAddress.getTokenUUID(tokenId);
if (_wallets[uuid] == address(0x0)) { return 0; }
return AaveSmartWalletB(_wallets[uuid]).getTotal(assetToken);
}
function getRewards(address contractAddress, uint256 tokenId, address _rewardToken) external override returns (uint256) {
uint256 uuid = contractAddress.getTokenUUID(tokenId);
if (_wallets[uuid] == address(0x0)) { return 0; }
return AaveSmartWalletB(_wallets[uuid]).getRewards(_rewardToken);
}
/***********************************|
| Only Controller |
|__________________________________*/
function energize(
address contractAddress,
uint256 tokenId,
address assetToken,
uint256 assetAmount
)
external
override
onlyController
returns (uint256 yieldTokensAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
// Deposit into Smart-Wallet
yieldTokensAmount = AaveSmartWalletB(wallet).deposit(assetToken, assetAmount, _referralCode);
// Log Event
emit WalletEnergized(contractAddress, tokenId, assetToken, assetAmount, yieldTokensAmount);
}
function discharge(
address receiver,
address contractAddress,
uint256 tokenId,
address assetToken,
address creatorRedirect
)
external
override
onlyController
returns (uint256 creatorAmount, uint256 receiverAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
require(wallet != address(0x0), "AWM:E-403");
(address creator, uint256 annuityPct) = _chargedSettings.getCreatorAnnuities(contractAddress, tokenId);
(, uint256 ownerInterest) = AaveSmartWalletB(wallet).getInterest(assetToken, annuityPct);
require(ownerInterest > 0, "AWM:E-412");
if (creatorRedirect != address(0)) {
creator = creatorRedirect;
}
// Discharge the full amount of interest
(creatorAmount, receiverAmount) = AaveSmartWalletB(wallet).withdrawAmount(receiver, creator, annuityPct, assetToken, ownerInterest);
// Log Event
emit WalletDischarged(contractAddress, tokenId, assetToken, creatorAmount, receiverAmount);
}
function dischargeAmount(
address receiver,
address contractAddress,
uint256 tokenId,
address assetToken,
uint256 assetAmount,
address creatorRedirect
)
external
override
onlyController
returns (uint256 creatorAmount, uint256 receiverAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
require(wallet != address(0x0), "AWM:E-403");
(address creator, uint256 annuityPct) = _chargedSettings.getCreatorAnnuities(contractAddress, tokenId);
(, uint256 ownerInterest) = AaveSmartWalletB(wallet).getInterest(assetToken, annuityPct);
require(assetAmount > 0 && ownerInterest >= assetAmount, "AWM:E-412");
if (creatorRedirect != address(0)) {
creator = creatorRedirect;
}
// Discharge a portion of the interest
(creatorAmount, receiverAmount) = AaveSmartWalletB(wallet).withdrawAmount(receiver, creator, annuityPct, assetToken, assetAmount);
// Log Event
emit WalletDischarged(contractAddress, tokenId, assetToken, creatorAmount, receiverAmount);
}
function dischargeAmountForCreator(
address receiver,
address contractAddress,
uint256 tokenId,
address creator,
address assetToken,
uint256 assetAmount
)
external
override
onlyController
returns (uint256 receiverAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
require(wallet != address(0x0), "AWM:E-403");
(, uint256 annuityPct) = _chargedSettings.getCreatorAnnuities(contractAddress, tokenId);
(uint256 creatorInterest,) = AaveSmartWalletB(wallet).getInterest(assetToken, annuityPct);
require(assetAmount > 0 && creatorInterest >= assetAmount, "AWM:E-412");
// Discharge a portion of the interest
receiverAmount = AaveSmartWalletB(wallet).withdrawAmountForCreator(receiver, annuityPct, assetToken, assetAmount);
// Log Event
emit WalletDischargedForCreator(contractAddress, tokenId, assetToken, creator, receiverAmount);
}
function release(
address receiver,
address contractAddress,
uint256 tokenId,
address assetToken,
address creatorRedirect
)
external
override
onlyController
returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
require(wallet != address(0x0), "AWM:E-403");
(address creator, uint256 annuityPct) = _chargedSettings.getCreatorAnnuities(contractAddress, tokenId);
if (creatorRedirect != address(0)) {
creator = creatorRedirect;
}
// Release Principal + Interest
principalAmount = AaveSmartWalletB(wallet).getPrincipal(assetToken);
(creatorAmount, receiverAmount) = AaveSmartWalletB(wallet).withdraw(receiver, creator, annuityPct, assetToken);
// Log Event
emit WalletReleased(contractAddress, tokenId, receiver, assetToken, principalAmount, creatorAmount, receiverAmount);
}
function releaseAmount(
address receiver,
address contractAddress,
uint256 tokenId,
address assetToken,
uint256 assetAmount,
address creatorRedirect
)
external
override
onlyController
returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
require(wallet != address(0x0), "AWM:E-403");
(address creator, uint256 annuityPct) = _chargedSettings.getCreatorAnnuities(contractAddress, tokenId);
if (creatorRedirect != address(0)) {
creator = creatorRedirect;
}
(, uint256 ownerInterest) = AaveSmartWalletB(wallet).getInterest(assetToken, annuityPct);
principalAmount = (ownerInterest < assetAmount) ? assetAmount.sub(ownerInterest) : 0;
// Release from interest first + principal if needed
(creatorAmount, receiverAmount) = AaveSmartWalletB(wallet).withdrawAmount(receiver, creator, annuityPct, assetToken, assetAmount);
// Log Event
emit WalletReleased(contractAddress, tokenId, receiver, assetToken, principalAmount, creatorAmount, receiverAmount);
}
function withdrawRewards(
address receiver,
address contractAddress,
uint256 tokenId,
address rewardsToken,
uint256 rewardsAmount
)
external
override
onlyController
returns (uint256 amount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
require(wallet != address(0x0), "AWM:E-403");
require(_rewardsTokenWhitelist[rewardsToken], "AWM:E-423");
// Withdraw Rewards to Receiver
amount = AaveSmartWalletB(wallet).withdrawRewards(receiver, rewardsToken, rewardsAmount);
// Log Event
emit WalletRewarded(contractAddress, tokenId, receiver, rewardsToken, amount);
}
function executeForAccount(
address contractAddress,
uint256 tokenId,
address externalAddress,
uint256 ethValue,
bytes memory encodedParams
)
external
override
onlyControllerOrExecutor
returns (bytes memory)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
return AaveSmartWalletB(wallet).executeForAccount(externalAddress, ethValue, encodedParams);
}
function refreshPrincipal(address contractAddress, uint256 tokenId, address assetToken)
external
override
onlyControllerOrExecutor
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
AaveSmartWalletB(wallet).refreshPrincipal(assetToken);
}
function getWalletAddressById(
address contractAddress,
uint256 tokenId,
address /* creator */,
uint256 /* annuityPct */
)
external
override
onlyControllerOrExecutor
returns (address)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
// Create Smart-Wallet if none exists
if (wallet == address(0x0)) {
wallet = _createWallet();
_wallets[uuid] = wallet;
emit NewSmartWallet(contractAddress, tokenId, wallet, address(0), 0);
}
return wallet;
}
/***********************************|
| Only Admin/DAO |
|__________________________________*/
function setAaveBridge(address aaveBridge) external onlyOwner {
require(aaveBridge != address(0x0), "AWM:E-403");
_aaveBridge = aaveBridge;
emit AaveBridgeSet(aaveBridge);
}
function setChargedSettings(address settings) external onlyOwner {
require(settings != address(0x0), "AWM:E-403");
_chargedSettings = IChargedSettings(settings);
emit ChargedSettingsSet(settings);
}
// ref: https://docs.aave.com/developers/developing-on-aave/the-protocol/lendingpool
function setReferralCode(uint256 referralCode) external onlyOwner {
_referralCode = referralCode;
}
function setValidRewardsToken(address rewardsToken, bool state) external onlyOwner {
_rewardsTokenWhitelist[rewardsToken] = state;
emit ValidRewardsTokenSet(rewardsToken, state);
}
/***********************************|
| Private Functions |
|__________________________________*/
function _createWallet()
internal
returns (address)
{
address newWallet = _createClone(_walletTemplate);
AaveSmartWalletB(newWallet).initialize(_aaveBridge);
return newWallet;
}
}
// 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
// WalletManagerBase.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IWalletManager.sol";
import "../interfaces/ISmartWallet.sol";
import "../lib/TokenInfo.sol";
import "./BlackholePrevention.sol";
/**
* @notice Wallet-Manager Base Contract
* @dev Non-upgradeable Contract
*/
abstract contract WalletManagerBase is Ownable, BlackholePrevention, IWalletManager {
using TokenInfo for address;
// The Controller Contract Address
address internal _controller;
// The Executor Contract Address
address internal _executor;
// Template Contract for creating Token Smart-Wallet Bridges
address internal _walletTemplate;
// TokenID => Token Smart-Wallet Address
mapping (uint256 => address) internal _wallets;
// State of Wallet Manager
bool internal _paused;
/***********************************|
| Public |
|__________________________________*/
function isPaused() external view override returns (bool) {
return _paused;
}
/***********************************|
| Only Admin/DAO |
|__________________________________*/
/**
* @dev Sets the Paused-state of the Wallet Manager
*/
function setPausedState(bool paused) external onlyOwner {
_paused = paused;
emit PausedStateSet(paused);
}
/**
* @dev Connects to the Charged Particles Controller
*/
function setController(address controller) external onlyOwner {
_controller = controller;
emit ControllerSet(controller);
}
/**
* @dev Connects to the ExecForAccount Controller
*/
function setExecutor(address executor) external onlyOwner {
_executor = executor;
emit ExecutorSet(executor);
}
function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount)
external
virtual
override
onlyOwner
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
_withdrawEther(receiver, amount);
return ISmartWallet(wallet).withdrawEther(receiver, amount);
}
function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount)
external
virtual
override
onlyOwner
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
_withdrawERC20(receiver, tokenAddress, amount);
return ISmartWallet(wallet).withdrawERC20(receiver, tokenAddress, amount);
}
function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId)
external
virtual
override
onlyOwner
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
_withdrawERC721(receiver, nftTokenAddress, nftTokenId);
return ISmartWallet(wallet).withdrawERC721(receiver, nftTokenAddress, nftTokenId);
}
/***********************************|
| Private Functions |
|__________________________________*/
function _getTokenUUID(address contractAddress, uint256 tokenId) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(contractAddress, tokenId)));
}
/**
* @dev Creates Contracts from a Template via Cloning
* see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md
*/
function _createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
/***********************************|
| Modifiers |
|__________________________________*/
/// @dev Throws if called by any account other than the Controller contract
modifier onlyController() {
require(_controller == msg.sender, "WMB:E-108");
_;
}
/// @dev Throws if called by any account other than the Executor contract
modifier onlyExecutor() {
require(_executor == msg.sender, "WMB:E-108");
_;
}
/// @dev Throws if called by any account other than the Controller or Executor contract
modifier onlyControllerOrExecutor() {
require(_executor == msg.sender || _controller == msg.sender, "WMB:E-108");
_;
}
// Throws if called by any account other than the Charged Particles Escrow Controller.
modifier whenNotPaused() {
require(_paused != true, "WMB:E-101");
_;
}
}
// SPDX-License-Identifier: MIT
// IChargedSettings.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "./IWalletManager.sol";
import "./IBasketManager.sol";
/**
* @notice Interface for Charged Settings
*/
interface IChargedSettings {
/***********************************|
| Public API |
|__________________________________*/
// function isContractOwner(address contractAddress, address account) external view returns (bool);
function getCreatorAnnuities(address contractAddress, uint256 tokenId) external returns (address creator, uint256 annuityPct);
function getCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId) external view returns (address);
function getTempLockExpiryBlocks() external view returns (uint256);
function getTimelockApprovals(address operator) external view returns (bool timelockAny, bool timelockOwn);
function getAssetRequirements(
address contractAddress,
address assetToken
) external view returns (
string memory requiredWalletManager,
bool energizeEnabled,
bool restrictedAssets,
bool validAsset,
uint256 depositCap,
uint256 depositMin,
uint256 depositMax,
bool invalidAsset
);
function getNftAssetRequirements(
address contractAddress,
address nftTokenAddress
) external view returns (
string memory requiredBasketManager,
bool basketEnabled,
uint256 maxNfts
);
/***********************************|
| Only NFT Creator |
|__________________________________*/
function setCreatorAnnuities(address contractAddress, uint256 tokenId, address creator, uint256 annuityPercent) external;
function setCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId, address receiver) external;
/***********************************|
| Only NFT Contract Owner |
|__________________________________*/
function setRequiredWalletManager(address contractAddress, string calldata walletManager) external;
function setRequiredBasketManager(address contractAddress, string calldata basketManager) external;
function setAssetTokenRestrictions(address contractAddress, bool restrictionsEnabled) external;
function setAllowedAssetToken(address contractAddress, address assetToken, bool isAllowed) external;
function setAssetTokenLimits(address contractAddress, address assetToken, uint256 depositMin, uint256 depositMax) external;
function setMaxNfts(address contractAddress, address nftTokenAddress, uint256 maxNfts) external;
/***********************************|
| Only Admin/DAO |
|__________________________________*/
function setAssetInvalidity(address assetToken, bool invalidity) external;
function enableNftContracts(address[] calldata contracts) external;
function setPermsForCharge(address contractAddress, bool state) external;
function setPermsForBasket(address contractAddress, bool state) external;
function setPermsForTimelockAny(address contractAddress, bool state) external;
function setPermsForTimelockSelf(address contractAddress, bool state) external;
/***********************************|
| Particle Events |
|__________________________________*/
event Initialized(address indexed initiator);
event ControllerSet(address indexed controllerAddress, string controllerId);
event DepositCapSet(address assetToken, uint256 depositCap);
event TempLockExpirySet(uint256 expiryBlocks);
event RequiredWalletManagerSet(address indexed contractAddress, string walletManager);
event RequiredBasketManagerSet(address indexed contractAddress, string basketManager);
event AssetTokenRestrictionsSet(address indexed contractAddress, bool restrictionsEnabled);
event AllowedAssetTokenSet(address indexed contractAddress, address assetToken, bool isAllowed);
event AssetTokenLimitsSet(address indexed contractAddress, address assetToken, uint256 assetDepositMin, uint256 assetDepositMax);
event MaxNftsSet(address indexed contractAddress, address indexed nftTokenAddress, uint256 maxNfts);
event AssetInvaliditySet(address indexed assetToken, bool invalidity);
event TokenCreatorConfigsSet(address indexed contractAddress, uint256 indexed tokenId, address indexed creatorAddress, uint256 annuityPercent);
event TokenCreatorAnnuitiesRedirected(address indexed contractAddress, uint256 indexed tokenId, address indexed redirectAddress);
event PermsSetForCharge(address indexed contractAddress, bool state);
event PermsSetForBasket(address indexed contractAddress, bool state);
event PermsSetForTimelockAny(address indexed contractAddress, bool state);
event PermsSetForTimelockSelf(address indexed contractAddress, bool state);
}
// SPDX-License-Identifier: MIT
// AaveSmartWallet.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. 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 "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../interfaces/IAaveBridge.sol";
import "../../lib/SmartWalletBaseB.sol";
/**
* @notice ERC20-Token Smart-Wallet for Aave Assets
* @dev Non-upgradeable Contract
*/
contract AaveSmartWalletB is SmartWalletBaseB {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant internal RAY = 1e27;
IAaveBridge internal _bridge;
uint256 internal _nftCreatorAmountDischarged;
mapping (address => address) internal _assetATokens;
/***********************************|
| Initialization |
|__________________________________*/
function initialize(
address aaveBridge
)
public
{
SmartWalletBaseB.initializeBase();
_bridge = IAaveBridge(aaveBridge);
}
/***********************************|
| Public |
|__________________________________*/
function isReserveActive(address assetToken) external view override returns (bool) {
return _bridge.isReserveActive(assetToken);
}
function getReserveInterestToken(address assetToken) external view override returns (address) {
return _bridge.getReserveInterestToken(assetToken);
}
function getPrincipal(address assetToken) external override returns (uint256) {
return _getPrincipal(assetToken);
}
function getInterest(address assetToken, uint256 creatorPct) external override returns (uint256 creatorInterest, uint256 ownerInterest) {
return _getInterest(assetToken, creatorPct);
}
function getTotal(address assetToken) external override returns (uint256) {
return _getTotal(assetToken);
}
function getRewards(address rewardToken) external override returns (uint256) {
return IERC20(rewardToken).balanceOf(address(this));
}
function deposit(
address assetToken,
uint256 assetAmount,
uint256 referralCode
)
external
override
onlyWalletManager
returns (uint256)
{
return _deposit(assetToken, assetAmount, referralCode);
}
function withdraw(
address receiver,
address creator,
uint256 creatorPct,
address assetToken
)
external
override
onlyWalletManager
returns (uint256 creatorAmount, uint256 receiverAmount)
{
uint256 walletPrincipal = _getPrincipal(assetToken);
(, uint256 ownerInterest) = _getInterest(assetToken, creatorPct);
return _withdraw(receiver, creator, creatorPct, assetToken, walletPrincipal.add(ownerInterest));
}
function withdrawAmount(
address receiver,
address creator,
uint256 creatorPct,
address assetToken,
uint256 assetAmount
)
external
override
onlyWalletManager
returns (uint256 creatorAmount, uint256 receiverAmount)
{
return _withdraw(receiver, creator, creatorPct, assetToken, assetAmount);
}
function withdrawAmountForCreator(
address receiver,
uint256 creatorPct,
address assetToken,
uint256 assetAmount
)
external
override
onlyWalletManager
returns (uint256 receiverAmount)
{
return _withdrawForCreator(receiver, creatorPct, assetToken, assetAmount);
}
function withdrawRewards(
address receiver,
address rewardsToken,
uint256 rewardsAmount
)
external
override
onlyWalletManager
returns (uint256)
{
return _withdrawRewards(receiver, rewardsToken, rewardsAmount);
}
function refreshPrincipal(address assetToken) external virtual override onlyWalletManager {
uint256 aTokenBalance = IERC20(_assetATokens[assetToken]).balanceOf(address(this));
if (_assetPrincipalBalance[assetToken] > aTokenBalance) {
_assetPrincipalBalance[assetToken] = aTokenBalance;
}
}
/***********************************|
| Private Functions |
|__________________________________*/
function _deposit(
address assetToken,
uint256 assetAmount,
uint256 referralCode
)
internal
returns (uint256)
{
_trackAssetToken(assetToken);
// Track Principal
_assetPrincipalBalance[assetToken] = _assetPrincipalBalance[assetToken].add(assetAmount);
// Deposit Assets into Aave (reverts on fail)
_sendToken(address(_bridge), assetToken, assetAmount);
uint256 aTokensAmount = _bridge.deposit(assetToken, assetAmount, referralCode);
// Return amount of aTokens transfered
return aTokensAmount;
}
function _withdraw(
address receiver,
address creator,
uint256 creatorPct,
address assetToken,
uint256 assetAmount
)
internal
returns (uint256 creatorAmount, uint256 receiverAmount)
{
uint256 walletPrincipal = _getPrincipal(assetToken);
(uint256 creatorInterest, uint256 ownerInterest) = _getInterest(assetToken, creatorPct);
// Withdraw from Interest only
if (assetAmount < ownerInterest) {
if (creatorInterest > 0) {
uint256 ratio = assetAmount.mul(RAY).div(ownerInterest);
creatorAmount = creatorInterest.add(_nftCreatorAmountDischarged).mul(ratio).div(RAY);
if (creatorAmount <= _nftCreatorAmountDischarged) {
_nftCreatorAmountDischarged = _nftCreatorAmountDischarged.sub(creatorAmount);
creatorAmount = 0;
}
else {
creatorAmount = creatorAmount.sub(_nftCreatorAmountDischarged);
_nftCreatorAmountDischarged = 0;
}
}
receiverAmount = assetAmount;
}
// Withdraw from Interest + Principal
else {
uint256 fromPrincipal = assetAmount.sub(ownerInterest);
if (fromPrincipal > walletPrincipal) {
fromPrincipal = walletPrincipal.sub(ownerInterest);
}
creatorAmount = creatorInterest;
receiverAmount = ownerInterest.add(fromPrincipal);
_nftCreatorAmountDischarged = 0;
// Track Principal
_assetPrincipalBalance[assetToken] = _assetPrincipalBalance[assetToken].sub(fromPrincipal);
}
// Send aTokens to Bridge
address aTokenAddress = _bridge.getReserveInterestToken(assetToken);
_sendToken(address(_bridge), aTokenAddress, receiverAmount.add(creatorAmount));
// Withdraw Assets for Creator
if (creatorAmount > 0) {
if (creator != address(0)) {
_bridge.withdraw(creator, assetToken, creatorAmount);
} else {
receiverAmount = receiverAmount.add(creatorAmount);
creatorAmount = 0;
}
}
// Withdraw Assets for Receiver
_bridge.withdraw(receiver, assetToken, receiverAmount);
}
function _withdrawForCreator(
address receiver,
uint256 creatorPct,
address assetToken,
uint256 assetAmount
)
internal
returns (uint256 receiverAmount)
{
(uint256 creatorInterest,) = _getInterest(assetToken, creatorPct);
if (creatorInterest == 0) { return 0; }
if (assetAmount > creatorInterest) {
assetAmount = creatorInterest;
}
_nftCreatorAmountDischarged = _nftCreatorAmountDischarged.add(assetAmount);
// Send aTokens to Bridge
address aTokenAddress = _bridge.getReserveInterestToken(assetToken);
_sendToken(address(_bridge), aTokenAddress, assetAmount);
// Withdraw Assets for Receiver on behalf of Creator
_bridge.withdraw(receiver, assetToken, assetAmount);
}
function _withdrawRewards(
address receiver,
address rewardsTokenAddress,
uint256 rewardsAmount
)
internal
returns (uint256)
{
address self = address(this);
IERC20 rewardsToken = IERC20(rewardsTokenAddress);
uint256 walletBalance = rewardsToken.balanceOf(self);
require(walletBalance >= rewardsAmount, "ASW:E-411");
// Transfer Rewards to Receiver
rewardsToken.safeTransfer(receiver, rewardsAmount);
return rewardsAmount;
}
function _getTotal(address assetToken) internal view returns (uint256) {
return _bridge.getTotalBalance(address(this), assetToken);
}
function _getInterest(address assetToken, uint256 creatorPct) internal view returns (uint256 creatorInterest, uint256 ownerInterest) {
uint256 total = _getTotal(assetToken);
uint256 principal = _getPrincipal(assetToken);
uint256 interest = total.sub(principal);
// Creator Royalties
if (creatorPct > 0) {
// Interest too small to calculate percentage;
if (interest <= PERCENTAGE_SCALE) {
// creatorInterest = interest.div(2); // split evenly?
creatorInterest = 0; // All to owner
}
// Calculate percentage for Creator
else {
creatorInterest = interest
.add(_nftCreatorAmountDischarged)
.mul(creatorPct)
.div(PERCENTAGE_SCALE)
.sub(_nftCreatorAmountDischarged);
}
}
// Owner Portion
ownerInterest = interest.sub(creatorInterest);
}
function _trackAssetToken(address assetToken) internal override {
if (!_assetTokens.contains(assetToken)) {
_assetTokens.add(assetToken);
address aTokenAddress = _bridge.getReserveInterestToken(assetToken);
_assetATokens[assetToken] = aTokenAddress;
}
}
function _sendToken(address to, address token, uint256 amount) internal {
IERC20(token).safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev 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
// IWalletManager.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Particle Wallet Manager interface
* @dev The wallet-manager for underlying assets attached to Charged Particles
* @dev Manages the link between NFTs and their respective Smart-Wallets
*/
interface IWalletManager {
event ControllerSet(address indexed controller);
event ExecutorSet(address indexed executor);
event PausedStateSet(bool isPaused);
event NewSmartWallet(address indexed contractAddress, uint256 indexed tokenId, address indexed smartWallet, address creator, uint256 annuityPct);
event WalletEnergized(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 assetAmount, uint256 yieldTokensAmount);
event WalletDischarged(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 creatorAmount, uint256 receiverAmount);
event WalletDischargedForCreator(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, address creator, uint256 receiverAmount);
event WalletReleased(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address assetToken, uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount);
event WalletRewarded(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address rewardsToken, uint256 rewardsAmount);
function isPaused() external view returns (bool);
function isReserveActive(address contractAddress, uint256 tokenId, address assetToken) external view returns (bool);
function getReserveInterestToken(address contractAddress, uint256 tokenId, address assetToken) external view returns (address);
function getTotal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256);
function getPrincipal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256);
function getInterest(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256 creatorInterest, uint256 ownerInterest);
function getRewards(address contractAddress, uint256 tokenId, address rewardToken) external returns (uint256);
function energize(address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount) external returns (uint256 yieldTokensAmount);
function discharge(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount);
function dischargeAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount);
function dischargeAmountForCreator(address receiver, address contractAddress, uint256 tokenId, address creator, address assetToken, uint256 assetAmount) external returns (uint256 receiverAmount);
function release(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount);
function releaseAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount);
function withdrawRewards(address receiver, address contractAddress, uint256 tokenId, address rewardsToken, uint256 rewardsAmount) external returns (uint256 amount);
function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory);
function refreshPrincipal(address contractAddress, uint256 tokenId, address assetToken) external;
function getWalletAddressById(address contractAddress, uint256 tokenId, address creator, uint256 annuityPct) external returns (address);
function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external;
function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external;
function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external;
}
// SPDX-License-Identifier: MIT
// ISmartWallet.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Charged Particles Smart Wallet
* @dev Manages holding and transferring assets of an NFT to a specific LP for Yield (if any),
*/
interface ISmartWallet {
function getAssetTokenCount() external view returns (uint256);
function getAssetTokenByIndex(uint256 index) external view returns (address);
function setNftCreator(address creator, uint256 annuityPct) external;
function isReserveActive(address assetToken) external view returns (bool);
function getReserveInterestToken(address assetToken) external view returns (address);
function getPrincipal(address assetToken) external returns (uint256);
function getInterest(address assetToken) external returns (uint256 creatorInterest, uint256 ownerInterest);
function getTotal(address assetToken) external returns (uint256);
function getRewards(address assetToken) external returns (uint256);
function deposit(address assetToken, uint256 assetAmount, uint256 referralCode) external returns (uint256);
function withdraw(address receiver, address creatorRedirect, address assetToken) external returns (uint256 creatorAmount, uint256 receiverAmount);
function withdrawAmount(address receiver, address creatorRedirect, address assetToken, uint256 assetAmount) external returns (uint256 creatorAmount, uint256 receiverAmount);
function withdrawAmountForCreator(address receiver, address assetToken, uint256 assetAmount) external returns (uint256 receiverAmount);
function withdrawRewards(address receiver, address rewardsToken, uint256 rewardsAmount) external returns (uint256);
function executeForAccount(address contractAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory);
function refreshPrincipal(address assetToken) external;
function withdrawEther(address payable receiver, uint256 amount) external;
function withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) external;
function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
// TokenInfo.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. 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 "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IERC721Chargeable.sol";
library TokenInfo {
function getTokenUUID(address contractAddress, uint256 tokenId) internal pure virtual returns (uint256) {
return uint256(keccak256(abi.encodePacked(contractAddress, tokenId)));
}
/// @dev DEPRECATED; Prefer TokenInfoProxy
function getTokenOwner(address contractAddress, uint256 tokenId) internal view virtual returns (address) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
return tokenInterface.ownerOf(tokenId);
}
/// @dev DEPRECATED; Prefer TokenInfoProxy
function getTokenCreator(address contractAddress, uint256 tokenId) internal view virtual returns (address) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
return tokenInterface.creatorOf(tokenId);
}
/// @dev DEPRECATED; Prefer TokenInfoProxy
/// @dev Checks if an account is the Owner of an External NFT contract
/// @param contractAddress The Address to the Contract of the NFT to check
/// @param account The Address of the Account to check
/// @return True if the account owns the contract
function isContractOwner(address contractAddress, address account) internal view virtual returns (bool) {
address contractOwner = IERC721Chargeable(contractAddress).owner();
return contractOwner != address(0x0) && contractOwner == account;
}
/// @dev DEPRECATED; Prefer TokenInfoProxy
/// @dev Checks if an account is the Creator of a Proton-based NFT
/// @param contractAddress The Address to the Contract of the Proton-based NFT to check
/// @param tokenId The Token ID of the Proton-based NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the creator of the Proton-based NFT
function isTokenCreator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenCreator = tokenInterface.creatorOf(tokenId);
return (sender == tokenCreator);
}
/// @dev DEPRECATED; Prefer TokenInfoProxy
/// @dev Checks if an account is the Creator of a Proton-based NFT or the Contract itself
/// @param contractAddress The Address to the Contract of the Proton-based NFT to check
/// @param tokenId The Token ID of the Proton-based NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the creator of the Proton-based NFT or the Contract itself
function isTokenContractOrCreator(address contractAddress, uint256 tokenId, address creator, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenCreator = tokenInterface.creatorOf(tokenId);
if (sender == contractAddress && creator == tokenCreator) { return true; }
return (sender == tokenCreator);
}
/// @dev DEPRECATED; Prefer TokenInfoProxy
/// @dev Checks if an account is the Owner or Operator of an External NFT
/// @param contractAddress The Address to the Contract of the External NFT to check
/// @param tokenId The Token ID of the External NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the Owner or Operator of the External NFT
function isErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenOwner = tokenInterface.ownerOf(tokenId);
return (sender == tokenOwner || tokenInterface.isApprovedForAll(tokenOwner, sender));
}
/**
* @dev Returns true if `account` is a contract.
* @dev Taken from OpenZeppelin library
*
* [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.
* @dev Taken from OpenZeppelin library
*
* 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, uint256 gasLimit) internal {
require(address(this).balance >= amount, "TokenInfo: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = (gasLimit > 0)
? recipient.call{ value: amount, gas: gasLimit }("")
: recipient.call{ value: amount }("");
require(success, "TokenInfo: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: MIT
// BlackholePrevention.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
/**
* @notice Prevents ETH or Tokens from getting stuck in a contract by allowing
* the Owner/DAO to pull them out on behalf of a user
* This is only meant to contracts that are not expected to hold tokens, but do handle transferring them.
*/
contract BlackholePrevention {
using Address for address payable;
using SafeERC20 for IERC20;
event WithdrawStuckEther(address indexed receiver, uint256 amount);
event WithdrawStuckERC20(address indexed receiver, address indexed tokenAddress, uint256 amount);
event WithdrawStuckERC721(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId);
event WithdrawStuckERC1155(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId, uint256 amount);
function _withdrawEther(address payable receiver, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (address(this).balance >= amount) {
receiver.sendValue(amount);
emit WithdrawStuckEther(receiver, amount);
}
}
function _withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC20(tokenAddress).balanceOf(address(this)) >= amount) {
IERC20(tokenAddress).safeTransfer(receiver, amount);
emit WithdrawStuckERC20(receiver, tokenAddress, amount);
}
}
function _withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC721(tokenAddress).ownerOf(tokenId) == address(this)) {
IERC721(tokenAddress).transferFrom(address(this), receiver, tokenId);
emit WithdrawStuckERC721(receiver, tokenAddress, tokenId);
}
}
function _withdrawERC1155(address payable receiver, address tokenAddress, uint256 tokenId, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC1155(tokenAddress).balanceOf(address(this), tokenId) >= amount) {
IERC1155(tokenAddress).safeTransferFrom(address(this), receiver, tokenId, amount, "");
emit WithdrawStuckERC1155(receiver, tokenAddress, tokenId, amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// IERC721Chargeable.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
interface IERC721Chargeable is IERC165Upgradeable {
function owner() external view returns (address);
function creatorOf(uint256 tokenId) external view returns (address);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address tokenOwner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address tokenOwner, address operator) external view returns (bool);
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 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.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
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;
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.6.2;
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 transfered 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.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
// IBasketManager.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Particle Basket Manager interface
* @dev The basket-manager for underlying assets attached to Charged Particles
* @dev Manages the link between NFTs and their respective Smart-Baskets
*/
interface IBasketManager {
event ControllerSet(address indexed controller);
event ExecutorSet(address indexed executor);
event PausedStateSet(bool isPaused);
event NewSmartBasket(address indexed contractAddress, uint256 indexed tokenId, address indexed smartBasket);
event BasketAdd(address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId, uint256 basketTokenAmount);
event BasketRemove(address indexed receiver, address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId, uint256 basketTokenAmount);
event BasketRewarded(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address rewardsToken, uint256 rewardsAmount);
function isPaused() external view returns (bool);
function getTokenTotalCount(address contractAddress, uint256 tokenId) external view returns (uint256);
function getTokenCountByType(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (uint256);
function prepareTransferAmount(uint256 nftTokenAmount) external;
function addToBasket(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool);
function removeFromBasket(address receiver, address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool);
function withdrawRewards(address receiver, address contractAddress, uint256 tokenId, address rewardsToken, uint256 rewardsAmount) external returns (uint256 amount);
function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory);
function getBasketAddressById(address contractAddress, uint256 tokenId) external returns (address);
function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external;
function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external;
function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external;
function withdrawERC1155(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// IAaveBridge.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
interface IAaveBridge {
function getReserveInterestToken(address assetToken) external view returns (address aTokenAddress);
function isReserveActive(address assetToken) external view returns (bool);
function getTotalBalance(address account, address assetToken) external view returns (uint256);
function deposit(address assetToken, uint256 assetAmount, uint256 referralCode) external returns (uint256);
function withdraw(address receiver, address assetToken, uint256 assetAmount) external;
}
// SPDX-License-Identifier: MIT
// SmartWalletBase.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../interfaces/ISmartWalletB.sol";
import "./BlackholePrevention.sol";
/**
* @notice ERC20-Token Smart-Wallet Base Contract
* @dev Non-upgradeable Contract
*/
abstract contract SmartWalletBaseB is ISmartWalletB, BlackholePrevention {
using EnumerableSet for EnumerableSet.AddressSet;
uint256 constant internal PERCENTAGE_SCALE = 1e4; // 10000 (100%)
address internal _walletManager;
EnumerableSet.AddressSet internal _assetTokens;
// Asset Token => Principal Balance
mapping (address => uint256) internal _assetPrincipalBalance;
/***********************************|
| Initialization |
|__________________________________*/
function initializeBase() public {
require(_walletManager == address(0x0), "SWB:E-002");
_walletManager = msg.sender;
}
/***********************************|
| Public |
|__________________________________*/
function getAssetTokenCount() external view virtual override returns (uint256) {
return _assetTokens.length();
}
function getAssetTokenByIndex(uint256 index) external view virtual override returns (address) {
if (index >= _assetTokens.length()) {
return address(0);
}
return _assetTokens.at(index);
}
function executeForAccount(
address contractAddress,
uint256 ethValue,
bytes memory encodedParams
)
external
override
onlyWalletManager
returns (bytes memory)
{
(bool success, bytes memory result) = contractAddress.call{value: ethValue}(encodedParams);
require(success, string(result));
return result;
}
/***********************************|
| Only Admin/DAO |
| (blackhole prevention) |
|__________________________________*/
function withdrawEther(address payable receiver, uint256 amount) external virtual override onlyWalletManager {
_withdrawEther(receiver, amount);
}
function withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) external virtual override onlyWalletManager {
_withdrawERC20(receiver, tokenAddress, amount);
}
function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external virtual override onlyWalletManager {
_withdrawERC721(receiver, tokenAddress, tokenId);
}
function withdrawERC1155(address payable receiver, address tokenAddress, uint256 tokenId, uint256 amount) external virtual override onlyWalletManager {
_withdrawERC1155(receiver, tokenAddress, tokenId, amount);
}
/***********************************|
| Private Functions |
|__________________________________*/
function _getPrincipal(address assetToken) internal view virtual returns (uint256) {
return _assetPrincipalBalance[assetToken];
}
function _trackAssetToken(address assetToken) internal virtual {
if (!_assetTokens.contains(assetToken)) {
_assetTokens.add(assetToken);
}
}
/***********************************|
| Modifiers |
|__________________________________*/
/// @dev Throws if called by any account other than the wallet manager
modifier onlyWalletManager() {
require(_walletManager == msg.sender, "SWB:E-109");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
// ISmartWallet.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Charged Particles Smart Wallet
* @dev Manages holding and transferring assets of an NFT to a specific LP for Yield (if any),
*/
interface ISmartWalletB {
function getAssetTokenCount() external view returns (uint256);
function getAssetTokenByIndex(uint256 index) external view returns (address);
function isReserveActive(address assetToken) external view returns (bool);
function getReserveInterestToken(address assetToken) external view returns (address);
function getPrincipal(address assetToken) external returns (uint256);
function getInterest(address assetToken, uint256 creatorPct) external returns (uint256 creatorInterest, uint256 ownerInterest);
function getTotal(address assetToken) external returns (uint256);
function getRewards(address assetToken) external returns (uint256);
function deposit(address assetToken, uint256 assetAmount, uint256 referralCode) external returns (uint256);
function withdraw(
address receiver,
address creator,
uint256 creatorPct,
address assetToken
) external returns (
uint256 creatorAmount,
uint256 receiverAmount
);
function withdrawAmount(
address receiver,
address creator,
uint256 creatorPct,
address assetToken,
uint256 assetAmount
) external returns (
uint256 creatorAmount,
uint256 receiverAmount
);
function withdrawAmountForCreator(
address receiver,
uint256 creatorPct,
address assetToken,
uint256 assetAmount
) external returns (
uint256 receiverAmount
);
function withdrawRewards(address receiver, address rewardsToken, uint256 rewardsAmount) external returns (uint256);
function executeForAccount(address contractAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory);
function refreshPrincipal(address assetToken) external;
function withdrawEther(address payable receiver, uint256 amount) external;
function withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) external;
function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external;
function withdrawERC1155(address payable receiver, address tokenAddress, uint256 tokenId, uint256 amount) external;
} | Sets the Paused-state of the Wallet Manager/ | function setPausedState(bool paused) external onlyOwner {
_paused = paused;
emit PausedStateSet(paused);
}
| 521,116 |
./full_match/137/0xbd331AF1E2Ae4813eA8e89b945AbB880aBCE5aFC/sources/contracts/Game.sol | TODO: check that msg.sender is the owner of the NFT | function AcceptOffer(address offerCreator, uint128 offerId, uint nft) public
{
GameOffer memory offer = _getOffer(offerCreator, offerId);
require(offer.creator != address(0), "offer not found");
IERC20(token).transferFrom(msg.sender, address(this), offer.bet);
uint128 id = lastAcceptId + 1;
lastAcceptId++;
accepts[offerId].push(GameAccept(id, offerId, msg.sender, nft, offer.bet));
emit Accept(offerId, id);
}
| 4,794,918 |
// CryptoTorch Source code
// copyright 2018 CryptoTorch <https://cryptotorch.io>
pragma solidity 0.4.19;
/**
* @title SafeMath
* Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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
*
* Owner rights:
* - change the name of the contract
* - change the name of the token
* - change the Proof of Stake difficulty
* - pause/unpause the contract
* - transfer ownership
*
* Owner CANNOT:
* - withdrawal funds
* - disable withdrawals
* - kill the contract
* - change the price of tokens
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
*
* Pausing the contract will only disable deposits,
* it will not prevent player dividend withdraws or token sales
*/
contract Pausable is Ownable {
event OnPause();
event OnUnpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
OnPause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
OnUnpause();
}
}
/**
* @title ReentrancyGuard
* Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
*/
contract ReentrancyGuard {
bool private reentrancyLock = false;
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
/**
* @title CryptoTorchToken
*/
contract CryptoTorchToken {
function contractBalance() public view returns (uint256);
function totalSupply() public view returns(uint256);
function balanceOf(address _playerAddress) public view returns(uint256);
function dividendsOf(address _playerAddress) public view returns(uint256);
function profitsOf(address _playerAddress) public view returns(uint256);
function referralBalanceOf(address _playerAddress) public view returns(uint256);
function sellPrice() public view returns(uint256);
function buyPrice() public view returns(uint256);
function calculateTokensReceived(uint256 _etherToSpend) public view returns(uint256);
function calculateEtherReceived(uint256 _tokensToSell) public view returns(uint256);
function sellFor(address _for, uint256 _amountOfTokens) public;
function withdrawFor(address _for) public;
function mint(address _to, uint256 _amountForTokens, address _referredBy) public payable returns(uint256);
}
/**
* @title Crypto-Torch Contract v1.2
*/
contract CryptoTorch is Pausable, ReentrancyGuard {
using SafeMath for uint256;
//
// Events
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
event onTorchPassed(
address indexed from,
address indexed to,
uint256 pricePaid
);
//
// Types
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
struct HighPrice {
uint256 price;
address owner;
}
struct HighMileage {
uint256 miles;
address owner;
}
struct PlayerData {
string name;
string note;
string coords;
uint256 dividends; // earnings waiting to be paid out
uint256 profits; // earnings already paid out
}
//
// Payout Structure
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Special Olympics Donations - 10%
// Token Pool - 90%
// - Referral - 10% of Token Pool
//
//
// Player Data
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
bool private migrationFinished = false;
uint8 public constant maxLeaders = 3; // Gold, Silver, Bronze
uint256 private _lowestHighPrice;
uint256 private _lowestHighMiles;
uint256 public totalDistanceRun;
uint256 public whaleIncreaseLimit = 2 ether;
uint256 public whaleMax = 20 ether;
HighPrice[maxLeaders] private _highestPrices;
HighMileage[maxLeaders] private _highestMiles;
address public torchRunner;
address public donationsReceiver_;
mapping (address => PlayerData) private playerData_;
CryptoTorchToken internal CryptoTorchToken_;
//
// Modifiers
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be possible
modifier antiWhalePrice(uint256 _amount) {
require(
whaleIncreaseLimit == 0 ||
(
_amount <= (whaleIncreaseLimit.add(_highestPrices[0].price)) &&
playerData_[msg.sender].dividends.add(playerData_[msg.sender].profits).add(_amount) <= whaleMax
)
);
_;
}
modifier onlyDuringMigration() {
require(!migrationFinished);
_;
}
//
// Contract Initialization
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
function CryptoTorch() public {}
/**
* Initializes the Contract Dependencies as well as the Holiday Mapping for OwnTheDay.io
*/
function initialize(address _torchRunner, address _tokenAddress) public onlyOwner {
torchRunner = _torchRunner;
CryptoTorchToken_ = CryptoTorchToken(_tokenAddress);
}
/**
* Migrate Leader Prices
*/
function migratePriceLeader(uint8 _leaderIndex, address _leaderAddress, uint256 _leaderPrice) public onlyOwner onlyDuringMigration {
require(_leaderIndex >= 0 && _leaderIndex < maxLeaders);
_highestPrices[_leaderIndex].owner = _leaderAddress;
_highestPrices[_leaderIndex].price = _leaderPrice;
if (_leaderIndex == maxLeaders-1) {
_lowestHighPrice = _leaderPrice;
}
}
/**
* Migrate Leader Miles
*/
function migrateMileageLeader(uint8 _leaderIndex, address _leaderAddress, uint256 _leaderMiles) public onlyOwner onlyDuringMigration {
require(_leaderIndex >= 0 && _leaderIndex < maxLeaders);
_highestMiles[_leaderIndex].owner = _leaderAddress;
_highestMiles[_leaderIndex].miles = _leaderMiles;
if (_leaderIndex == maxLeaders-1) {
_lowestHighMiles = _leaderMiles;
}
}
/**
*
*/
function finishMigration() public onlyOwner onlyDuringMigration {
migrationFinished = true;
}
/**
*
*/
function isMigrationFinished() public view returns (bool) {
return migrationFinished;
}
/**
* Sets the external contract address of the Token Contract
*/
function setTokenContract(address _tokenAddress) public onlyOwner {
CryptoTorchToken_ = CryptoTorchToken(_tokenAddress);
}
/**
* Set the Contract Donations Receiver
* - Set to the Special Olympics Donations Address
*/
function setDonationsReceiver(address _receiver) public onlyOwner {
donationsReceiver_ = _receiver;
}
/**
* The Max Price-Paid Limit for Whales during the Anti-Whale Phase
*/
function setWhaleMax(uint256 _max) public onlyOwner {
whaleMax = _max;
}
/**
* The Max Price-Increase Limit for Whales during the Anti-Whale Phase
*/
function setWhaleIncreaseLimit(uint256 _limit) public onlyOwner {
whaleIncreaseLimit = _limit;
}
//
// Public Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* Sets the Nickname for an Account Address
*/
function setAccountNickname(string _nickname) public whenNotPaused {
require(msg.sender != address(0));
require(bytes(_nickname).length > 0);
playerData_[msg.sender].name = _nickname;
}
/**
* Gets the Nickname for an Account Address
*/
function getAccountNickname(address _playerAddress) public view returns (string) {
return playerData_[_playerAddress].name;
}
/**
* Sets the Note for an Account Address
*/
function setAccountNote(string _note) public whenNotPaused {
require(msg.sender != address(0));
playerData_[msg.sender].note = _note;
}
/**
* Gets the Note for an Account Address
*/
function getAccountNote(address _playerAddress) public view returns (string) {
return playerData_[_playerAddress].note;
}
/**
* Sets the Note for an Account Address
*/
function setAccountCoords(string _coords) public whenNotPaused {
require(msg.sender != address(0));
playerData_[msg.sender].coords = _coords;
}
/**
* Gets the Note for an Account Address
*/
function getAccountCoords(address _playerAddress) public view returns (string) {
return playerData_[_playerAddress].coords;
}
/**
* Take the Torch!
* The Purchase Price is Paid to the Previous Torch Holder, and is also used
* as the Purchasers Mileage Multiplier
*/
function takeTheTorch(address _referredBy) public nonReentrant whenNotPaused payable {
takeTheTorch_(msg.value, msg.sender, _referredBy);
}
/**
* Payments made directly to this contract are treated as direct Donations to the Special Olympics.
* - Note: payments made directly to the contract do not receive tokens. Tokens
* are only available via "takeTheTorch()" or through the Dapp at https://cryptotorch.io
*/
function() payable public {
if (msg.value > 0 && donationsReceiver_ != 0x0) {
donationsReceiver_.transfer(msg.value); // donations? Thank you! :)
}
}
/**
* Sell some tokens for Ether
*/
function sell(uint256 _amountOfTokens) public {
CryptoTorchToken_.sellFor(msg.sender, _amountOfTokens);
}
/**
* Withdraw the earned Dividends to Ether
* - Includes Torch + Token Dividends and Token Referral Bonuses
*/
function withdrawDividends() public returns (uint256) {
CryptoTorchToken_.withdrawFor(msg.sender);
return withdrawFor_(msg.sender);
}
//
// Helper Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* View the total balance of this contract
*/
function torchContractBalance() public view returns (uint256) {
return this.balance;
}
/**
* View the total balance of the token contract
*/
function tokenContractBalance() public view returns (uint256) {
return CryptoTorchToken_.contractBalance();
}
/**
* Retrieve the total token supply.
*/
function totalSupply() public view returns(uint256) {
return CryptoTorchToken_.totalSupply();
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _playerAddress) public view returns(uint256) {
return CryptoTorchToken_.balanceOf(_playerAddress);
}
/**
* Retrieve the token dividend balance of any single address.
*/
function tokenDividendsOf(address _playerAddress) public view returns(uint256) {
return CryptoTorchToken_.dividendsOf(_playerAddress);
}
/**
* Retrieve the referral dividend balance of any single address.
*/
function referralDividendsOf(address _playerAddress) public view returns(uint256) {
return CryptoTorchToken_.referralBalanceOf(_playerAddress);
}
/**
* Retrieve the dividend balance of any single address.
*/
function torchDividendsOf(address _playerAddress) public view returns(uint256) {
return playerData_[_playerAddress].dividends;
}
/**
* Retrieve the dividend balance of any single address.
*/
function profitsOf(address _playerAddress) public view returns(uint256) {
return playerData_[_playerAddress].profits.add(CryptoTorchToken_.profitsOf(_playerAddress));
}
/**
* Return the sell price of 1 individual token.
*/
function sellPrice() public view returns(uint256) {
return CryptoTorchToken_.sellPrice();
}
/**
* Return the buy price of 1 individual token.
*/
function buyPrice() public view returns(uint256) {
return CryptoTorchToken_.buyPrice();
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _etherToSpend) public view returns(uint256) {
uint256 forTokens = _etherToSpend.sub(_etherToSpend.div(10)); // 90% for Tokens
return CryptoTorchToken_.calculateTokensReceived(forTokens);
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEtherReceived(uint256 _tokensToSell) public view returns(uint256) {
return CryptoTorchToken_.calculateEtherReceived(_tokensToSell);
}
/**
* Get the Max Price of the Torch during the Anti-Whale Phase
*/
function getMaxPrice() public view returns (uint256) {
if (whaleIncreaseLimit == 0) { return 0; } // no max price
return whaleIncreaseLimit.add(_highestPrices[0].price);
}
/**
* Get the Highest Price per each Medal Leader
*/
function getHighestPriceAt(uint _index) public view returns (uint256) {
require(_index >= 0 && _index < maxLeaders);
return _highestPrices[_index].price;
}
/**
* Get the Highest Price Owner per each Medal Leader
*/
function getHighestPriceOwnerAt(uint _index) public view returns (address) {
require(_index >= 0 && _index < maxLeaders);
return _highestPrices[_index].owner;
}
/**
* Get the Highest Miles per each Medal Leader
*/
function getHighestMilesAt(uint _index) public view returns (uint256) {
require(_index >= 0 && _index < maxLeaders);
return _highestMiles[_index].miles;
}
/**
* Get the Highest Miles Owner per each Medal Leader
*/
function getHighestMilesOwnerAt(uint _index) public view returns (address) {
require(_index >= 0 && _index < maxLeaders);
return _highestMiles[_index].owner;
}
//
// Internal Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* Take the Torch! And receive KMS Tokens!
*/
function takeTheTorch_(uint256 _amountPaid, address _takenBy, address _referredBy) internal antiWhalePrice(_amountPaid) returns (uint256) {
require(_takenBy != address(0));
require(_amountPaid >= 1 finney);
require(_takenBy != torchRunner); // Torch must be passed on
if (_referredBy == address(this)) { _referredBy = address(0); }
// Calculate Portions
uint256 forDonations = _amountPaid.div(10);
uint256 forTokens = _amountPaid.sub(forDonations);
// Pass the Torch
onTorchPassed(torchRunner, _takenBy, _amountPaid);
torchRunner = _takenBy;
// Grant Mileage Tokens to Torch Holder
uint256 mintedTokens = CryptoTorchToken_.mint.value(forTokens)(torchRunner, forTokens, _referredBy);
if (totalDistanceRun < CryptoTorchToken_.totalSupply()) {
totalDistanceRun = CryptoTorchToken_.totalSupply();
}
// Update LeaderBoards
updateLeaders_(torchRunner, _amountPaid);
// Handle Payouts
playerData_[donationsReceiver_].profits = playerData_[donationsReceiver_].profits.add(forDonations);
donationsReceiver_.transfer(forDonations);
return mintedTokens;
}
/**
* Withdraw the earned Torch Dividends to Ether
* - Does not touch Token Dividends or Token Referral Bonuses
*/
function withdrawFor_(address _for) internal returns (uint256) {
uint256 torchDividends = playerData_[_for].dividends;
if (playerData_[_for].dividends > 0) {
playerData_[_for].dividends = 0;
playerData_[_for].profits = playerData_[_for].profits.add(torchDividends);
_for.transfer(torchDividends);
}
return torchDividends;
}
/**
* Update the Medal Leader Boards
*/
function updateLeaders_(address _torchRunner, uint256 _amountPaid) internal {
// Owner can't be leader; conflict of interest
if (_torchRunner == owner) { return; }
// Update Highest Prices
if (_amountPaid > _lowestHighPrice) {
updateHighestPrices_(_amountPaid, _torchRunner);
}
// Update Highest Mileage
uint256 tokenBalance = CryptoTorchToken_.balanceOf(_torchRunner);
if (tokenBalance > _lowestHighMiles) {
updateHighestMiles_(tokenBalance, _torchRunner);
}
}
/**
* Update the Medal Leaderboard for the Highest Price
*/
function updateHighestPrices_(uint256 _price, address _owner) internal {
uint256 newPos = maxLeaders;
uint256 oldPos = maxLeaders;
uint256 i;
HighPrice memory tmp;
// Determine positions
for (i = maxLeaders-1; i >= 0; i--) {
if (_price >= _highestPrices[i].price) {
newPos = i;
}
if (_owner == _highestPrices[i].owner) {
oldPos = i;
}
if (i == 0) { break; } // prevent i going below 0
}
// Insert or update leader
if (newPos < maxLeaders) {
if (oldPos < maxLeaders-1) {
// update price for existing leader
_highestPrices[oldPos].price = _price;
if (newPos != oldPos) {
// swap
tmp = _highestPrices[newPos];
_highestPrices[newPos] = _highestPrices[oldPos];
_highestPrices[oldPos] = tmp;
}
} else {
// shift down
for (i = maxLeaders-1; i > newPos; i--) {
_highestPrices[i] = _highestPrices[i-1];
}
// insert
_highestPrices[newPos].price = _price;
_highestPrices[newPos].owner = _owner;
}
// track lowest value
_lowestHighPrice = _highestPrices[maxLeaders-1].price;
}
}
/**
* Update the Medal Leaderboard for the Highest Miles
*/
function updateHighestMiles_(uint256 _miles, address _owner) internal {
uint256 newPos = maxLeaders;
uint256 oldPos = maxLeaders;
uint256 i;
HighMileage memory tmp;
// Determine positions
for (i = maxLeaders-1; i >= 0; i--) {
if (_miles >= _highestMiles[i].miles) {
newPos = i;
}
if (_owner == _highestMiles[i].owner) {
oldPos = i;
}
if (i == 0) { break; } // prevent i going below 0
}
// Insert or update leader
if (newPos < maxLeaders) {
if (oldPos < maxLeaders-1) {
// update miles for existing leader
_highestMiles[oldPos].miles = _miles;
if (newPos != oldPos) {
// swap
tmp = _highestMiles[newPos];
_highestMiles[newPos] = _highestMiles[oldPos];
_highestMiles[oldPos] = tmp;
}
} else {
// shift down
for (i = maxLeaders-1; i > newPos; i--) {
_highestMiles[i] = _highestMiles[i-1];
}
// insert
_highestMiles[newPos].miles = _miles;
_highestMiles[newPos].owner = _owner;
}
// track lowest value
_lowestHighMiles = _highestMiles[maxLeaders-1].miles;
}
}
} | Get the Max Price of the Torch during the Anti-Whale Phase/ | function getMaxPrice() public view returns (uint256) {
return whaleIncreaseLimit.add(_highestPrices[0].price);
}
| 1,180,477 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// 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;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@chainlink/contracts/src/v0.8/VRFConsumerBase.sol';
import 'hardhat/console.sol';
interface IERC721Custom {
function mint(address user, uint256 tokenId) external;
}
interface IRouter {
function WETH() external view returns (address);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
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);
}
contract Minting is VRFConsumerBase, Ownable {
IERC721Custom public nft;
uint256 public startDate;
bytes32 public whitelistRoot;
bytes32 public OGRoot;
uint256 public ogQuantity = 4;
uint256 public whitlistQuantity = 2;
uint256 public maxQuantity = 20;
uint256 public duration = 7 days;
bytes32 internal keyHash;
uint256 internal fee;
mapping(address => bytes32) public requestIds;
mapping(bytes32 => uint256) public mintAmount;
mapping(bytes32 => bool) public unclaim;
mapping(bytes32 => uint256) public randomNumbers;
mapping(bytes32 => bool) public filled;
IRouter public router;
mapping(address => uint256) public minted;
mapping(uint256 => uint256) public indexes;
uint256 public amount = 10_000;
/// @dev verifies ogs
/// @param proof array of bytes for merkle tree verifing
/// @param root tree's root
/// @param leaf keccak256 of user address
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) public pure returns (bool) {
bytes32 hash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
hash = hash < proofElement
? keccak256(abi.encodePacked(hash, proofElement))
: keccak256(abi.encodePacked(proofElement, hash));
}
return hash == root;
}
function claim() external {
bytes32 requestId = requestIds[msg.sender];
require(unclaim[requestId] && filled[requestId]);
uint256 quantity = mintAmount[requestId];
uint256 randomness = randomNumbers[requestId];
for (uint256 i = 0; i < quantity; i++) {
uint256 randomIndex = range(
uint256(keccak256(abi.encodePacked(randomness, i))),
1,
amount + 1
);
uint256 randomTokenId = 0;
if (indexes[randomIndex] == 0) randomTokenId = randomIndex;
else randomTokenId = indexes[randomIndex];
uint256 newIndex = indexes[amount];
if (newIndex == 0) indexes[randomIndex] = amount;
else indexes[randomIndex] = indexes[amount];
amount -= 1;
nft.mint(msg.sender, randomTokenId);
}
unclaim[requestId] = false;
}
/// @dev mints nft to user
/// @param quantity amount of nft to mint
/// @param proof array of bytes for merkle tree verifing
function mint(uint256 quantity, bytes32[] memory proof) external payable {
require(
(startDate != 0) && (block.timestamp < startDate + duration),
'Mint have not started yet'
);
require(!unclaim[requestIds[msg.sender]]);
require(amount > 0, 'Max out');
uint256 mintQuantity = 0;
if (block.timestamp - startDate < 1 days) {
bytes32 leaf = keccak256(abi.encode(msg.sender));
bool isOG = verify(proof, OGRoot, leaf);
bool isWhitelist = verify(proof, whitelistRoot, leaf);
require(isOG || isWhitelist, 'You cant mint the nft right now');
if (isOG) {
mintQuantity = (quantity > (ogQuantity - minted[msg.sender]))
? ogQuantity - minted[msg.sender]
: quantity;
} else if (isWhitelist) {
mintQuantity = (quantity > whitlistQuantity - minted[msg.sender])
? whitlistQuantity - minted[msg.sender]
: quantity;
}
} else {
mintQuantity = quantity > maxQuantity ? maxQuantity : quantity;
}
mintQuantity = mintQuantity > amount ? amount : mintQuantity;
require(mintQuantity != 0, 'You cant mint zero');
minted[msg.sender] += mintQuantity;
_feeManagment();
bytes32 requestId = _getRandomNumber();
unclaim[requestId] = true;
mintAmount[requestId] = mintQuantity;
requestIds[msg.sender] = requestId;
}
function startMinting() external onlyOwner {
startDate = block.timestamp;
}
function stopMinting() external onlyOwner {
startDate = 0;
}
function changeDuration(uint256 _duration) external onlyOwner {
duration = _duration;
}
/// @dev sets og Root
/// @param _OGRoot OG's tree root
function saveRootOg(bytes32 _OGRoot) external onlyOwner {
OGRoot = _OGRoot;
}
/// @dev sets whitelist Root
/// @param _whitelistRoot whitelist's tree root
function saveRootWhitelist(bytes32 _whitelistRoot) external onlyOwner {
whitelistRoot = _whitelistRoot;
}
/// @dev fee of one spin
/// @return fee amount of fee for one spin in ETH
function feeETH() public view returns (uint256) {
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = address(LINK);
return router.getAmountsIn(fee, path)[0];
}
/// @dev swaps provided amount of ETH to LINK to cover the fee, and transfers back what is left
function _feeManagment() internal {
require(msg.value >= feeETH(), 'Not enough WBNB to pay fee');
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = address(LINK);
uint256[] memory amounts = router.swapETHForExactTokens{value: msg.value}(
fee,
path,
address(this),
block.timestamp
);
payable(msg.sender).transfer(msg.value - amounts[0]);
}
/// @dev requests random number from chainlink nodes
function _getRandomNumber() internal returns (bytes32) {
require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK');
return requestRandomness(keyHash, fee);
}
/// @inheritdoc VRFConsumerBase
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomNumbers[requestId] = randomness;
filled[requestId] = true;
}
/// @dev to recieve native from router
receive() external payable {}
/// @dev maps number to range from `from` (includes) to `to` (excludes)
/// @param number initial number
/// @param from start of range
/// @param to stop of range
/// @return map result
function range(
uint256 number,
uint256 from,
uint256 to
) public pure returns (uint256) {
return (number % (to - from)) + from;
}
constructor(
address nft_,
address router_,
address vrfCoordinator_,
address link_,
bytes32 keyHash_,
uint256 fee_
) VRFConsumerBase(vrfCoordinator_, link_) {
nft = IERC721Custom(nft_);
router = IRouter(router_);
keyHash = keyHash_;
fee = fee_;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import '@openzeppelin/contracts/access/Ownable.sol';
import {IERC721Custom} from './Minting.sol';
interface OldMinting {
function amount() external view returns (uint256);
function indexes(uint256 index) external view returns (uint256);
}
contract PublicMinting is Ownable {
IERC721Custom public nft;
OldMinting public minting;
uint256 public startTimestamp;
uint256 public duration = 7 days;
uint256 public maxQuantity = 20;
mapping(uint256 => uint256) public indexes;
uint256 public amount;
event Start(uint256 indexed timestamp, address indexed user);
event Stop(uint256 indexed timestamp, address indexed user);
event Mint(uint256 indexed timestamp, address indexed user, uint256 tokenId);
event SyncAmount(uint256 indexed timestamp, address indexed user, uint256 amount);
event SetMaxQuantity(
uint256 indexed timestamp,
address indexed user,
uint256 maxQuantity
);
event SetDuration(uint256 indexed timestamp, address indexed user, uint256 duration);
/// @dev mints nft to user
/// @param quantity amount of nft to mint
function mint(uint256 quantity) external {
require(startTimestamp > 0, 'Minting has not been started');
_mint(quantity, msg.sender);
}
/// @dev mints nfts for user by owner
/// @param quantities amount of nft to mint
/// @param users users
function mintMass(uint256[] memory quantities, address[] memory users)
external
onlyOwner
{
require(startTimestamp == 0, 'Minting has been started');
require(quantities.length == users.length, 'Different sizes');
uint256 length = quantities.length;
for (uint256 i = 0; i < length; i++) {
_mint(quantities[i], users[i]);
}
}
function _mint(uint256 quantity, address user) internal {
// quantity = min(quantity, maxQuantity, amount)
quantity = quantity > maxQuantity ? maxQuantity : quantity;
quantity = quantity > amount ? amount : quantity;
// ---------------------------------------------
for (uint256 i = 0; i < quantity; i++) {
uint256 randomness = addSalt(getRandomNumber(), i);
uint256 index = range(randomness, 1, amount + 1);
uint256 realIndex = getIndex(index);
setIndex(index);
nft.mint(user, realIndex);
emit Mint(block.timestamp, user, realIndex);
}
}
/// @dev returns real index from old minting contract
function getIndex(uint256 index) internal view returns (uint256) {
uint256 result = indexes[index];
if (result == 0) result = minting.indexes(index);
if (result == 0) result = index;
return result;
}
/// @dev sets index of new tokenId
function setIndex(uint256 index) internal {
uint256 result = indexes[amount];
if (result == 0) result = minting.indexes(amount);
if (result == 0) result = amount;
indexes[index] = result;
amount--;
}
/// @dev starts minting
function start() external onlyOwner {
startTimestamp = block.timestamp;
if (amount == 0) amount = minting.amount();
emit Start(block.timestamp, msg.sender);
}
/// @dev stops minting
function stop() external onlyOwner {
startTimestamp = 0;
emit Stop(block.timestamp, msg.sender);
}
/// @dev sets maxQuantity
/// @param maxQuantity_ new max quantity
function setMaxQuantity(uint256 maxQuantity_) external onlyOwner {
maxQuantity = maxQuantity_;
emit SetMaxQuantity(block.timestamp, msg.sender, maxQuantity_);
}
/// @dev sets new duration of public mint from startTimestamp
/// @param duration_ new duration of minting
function setDuration(uint256 duration_) external onlyOwner {
duration = duration_;
emit SetDuration(block.timestamp, msg.sender, duration_);
}
/// @dev syncs amount from old minting
function syncAmount() external onlyOwner {
amount = minting.amount();
emit SyncAmount(block.timestamp, msg.sender, amount);
}
/// @dev generates random number
function getRandomNumber() public view returns (uint256) {
return
uint256(
keccak256(abi.encodePacked(block.difficulty, block.timestamp, msg.sender))
);
}
/// @dev maps number to range from `from` (includes) to `to` (excludes)
/// @param number initial number
/// @param from start of range
/// @param to stop of range
/// @return map result
function range(
uint256 number,
uint256 from,
uint256 to
) public pure returns (uint256) {
return (number % (to - from)) + from;
}
/// @dev adds salt to value with hash function
/// @param value which salting
/// @param salt salt
function addSalt(uint256 value, uint256 salt) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(value, salt)));
}
/// @dev contructor
constructor(address nft_, address minting_) {
nft = IERC721Custom(nft_);
minting = OldMinting(minting_);
}
}
// 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));
}
} | swaps provided amount of ETH to LINK to cover the fee, and transfers back what is left | function _feeManagment() internal {
require(msg.value >= feeETH(), 'Not enough WBNB to pay fee');
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = address(LINK);
fee,
path,
address(this),
block.timestamp
);
payable(msg.sender).transfer(msg.value - amounts[0]);
}
| 14,738,794 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract AirdropPush {
using SafeERC20 for IERC20;
/// @notice Used to distribute preToke to seed investors. Can be used for any ERC20 airdrop
/// @param token IERC20 interface connected to distrubuted token contract
/// @param accounts Account addresses to distribute tokens to
/// @param amounts Amounts to be sent to corresponding addresses
function distribute(
IERC20 token,
address[] calldata accounts,
uint256[] calldata amounts
) external {
require(accounts.length == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < accounts.length; i++) {
token.safeTransferFrom(msg.sender, accounts[i], amounts[i]);
}
}
}
// 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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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.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.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@0x/contracts-zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol";
import "../interfaces/IWallet.sol";
contract ZeroExTradeWallet is IWallet, Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
INativeOrdersFeature public zeroExRouter;
address public manager;
EnumerableSet.AddressSet internal tokens;
modifier onlyManager() {
require(msg.sender == manager, "INVALID_MANAGER");
_;
}
constructor(address newRouter, address newManager) public {
require(newRouter != address(0), "INVALID_ROUTER");
require(newManager != address(0), "INVALID_MANAGER");
zeroExRouter = INativeOrdersFeature(newRouter);
manager = newManager;
}
function getTokens() external view returns (address[] memory) {
address[] memory returnData = new address[](tokens.length());
for (uint256 i = 0; i < tokens.length(); i++) {
returnData[i] = tokens.at(i);
}
return returnData;
}
// solhint-disable-next-line no-empty-blocks
function registerAllowedOrderSigner(address signer, bool allowed) external override onlyOwner {
require(signer != address(0), "INVALID_SIGNER");
zeroExRouter.registerAllowedOrderSigner(signer, allowed);
}
function deposit(address[] calldata depositTokens, uint256[] calldata amounts)
external
override
onlyManager
nonReentrant
{
uint256 tokensLength = depositTokens.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
require(tokens.contains(depositTokens[i]), "ADDRESS_NOT_WHITELISTED");
IERC20(depositTokens[i]).safeTransferFrom(msg.sender, address(this), amounts[i]);
// NOTE: approval must be done after transferFrom; balance is checked in the approval
_approve(IERC20(depositTokens[i]));
}
}
function withdraw(address[] calldata tokensToWithdraw, uint256[] calldata amounts)
external
override
onlyManager
nonReentrant
{
uint256 tokensLength = tokensToWithdraw.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
require(tokens.contains(tokensToWithdraw[i]), "ADDRESS_NOT_WHITELISTED");
IERC20(tokensToWithdraw[i]).safeTransfer(msg.sender, amounts[i]);
}
}
function whitelistTokens(address[] calldata tokensToAdd) external onlyOwner {
for (uint256 i = 0; i < tokensToAdd.length; i++) {
if (!tokens.contains(tokensToAdd[i])) {
tokens.add(tokensToAdd[i]);
}
}
}
function removeWhitelistedTokens(address[] calldata tokensToRemove) external onlyOwner {
for (uint256 i = 0; i < tokensToRemove.length; i++) {
bool removed = tokens.remove(tokensToRemove[i]);
require(removed, "DOES_NOT_EXIST");
}
}
function _approve(IERC20 token) internal {
// Approve the zeroExRouter's allowance to max if the allowance ever drops below the balance of the token held
uint256 allowance = token.allowance(address(this), address(zeroExRouter));
if (allowance < token.balanceOf(address(this))) {
uint256 amount = token.balanceOf(address(this)).sub(allowance);
token.safeIncreaseAllowance(address(zeroExRouter), amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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/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: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
import "./INativeOrdersEvents.sol";
/// @dev Feature for interacting with limit orders.
interface INativeOrdersFeature is
INativeOrdersEvents
{
/// @dev Transfers protocol fees from the `FeeCollector` pools into
/// the staking contract.
/// @param poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds)
external;
/// @dev Fill a limit order. The taker and sender will be the caller.
/// @param order The limit order. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 makerTokenFilledAmount);
/// @dev Fill a limit order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// `msg.sender` (not `sender`).
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @param sender The order sender.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker,
address sender
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order. Internal variant.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Cancel a single limit order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The limit order.
function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order)
external;
/// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The RFQ order.
function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order)
external;
/// @dev Mark what tx.origin addresses are allowed to fill an order that
/// specifies the message sender as its txOrigin.
/// @param origins An array of origin addresses to update.
/// @param allowed True to register, false to unregister.
function registerAllowedRfqOrigins(address[] memory origins, bool allowed)
external;
/// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The limit orders.
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders)
external;
/// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The RFQ orders.
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Get the order info for a limit order.
/// @param order The limit order.
/// @return orderInfo Info about the order.
function getLimitOrderInfo(LibNativeOrder.LimitOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the order info for an RFQ order.
/// @param order The RFQ order.
/// @return orderInfo Info about the order.
function getRfqOrderInfo(LibNativeOrder.RfqOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the canonical hash of a limit order.
/// @param order The limit order.
/// @return orderHash The order hash.
function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the canonical hash of an RFQ order.
/// @param order The RFQ order.
/// @return orderHash The order hash.
function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the protocol fee multiplier. This should be multiplied by the
/// gas price to arrive at the required protocol fee to fill a native order.
/// @return multiplier The protocol fee multiplier.
function getProtocolFeeMultiplier()
external
view
returns (uint32 multiplier);
/// @dev Get order info, fillable amount, and signature validity for a limit order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The limit order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getLimitOrderRelevantState(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Get order info, fillable amount, and signature validity for an RFQ order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Batch version of `getLimitOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getLimitOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The limit orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetLimitOrderRelevantStates(
LibNativeOrder.LimitOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Batch version of `getRfqOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getRfqOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The RFQ orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetRfqOrderRelevantStates(
LibNativeOrder.RfqOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Register a signer who can sign on behalf of msg.sender
/// This allows one to sign on behalf of a contract that calls this function
/// @param signer The address from which you plan to generate signatures
/// @param allowed True to register, false to unregister.
function registerAllowedOrderSigner(
address signer,
bool allowed
)
external;
/// @dev checks if a given address is registered to sign on behalf of a maker address
/// @param maker The maker address encoded in an order (can be a contract)
/// @param signer The address that is providing a signature
function isValidOrderSigner(
address maker,
address signer
)
external
view
returns (bool isAllowed);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IWallet {
function registerAllowedOrderSigner(address signer, bool allowed) external;
function deposit(address[] calldata tokens, uint256[] calldata amounts) external;
function withdraw(address[] calldata tokens, uint256[] calldata amounts) external;
}
// 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 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
interface IERC20TokenV06 {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address to, uint256 value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param from The address of the sender
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (bool);
/// @dev `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @dev Get the balance of `owner`.
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
/// @dev Get the allowance for `spender` to spend from `owner`.
/// @param owner The address of the account owning tokens
/// @param spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender)
external
view
returns (uint256);
/// @dev Get the number of decimals this token has.
function decimals()
external
view
returns (uint8);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../../errors/LibSignatureRichErrors.sol";
/// @dev A library for validating signatures.
library LibSignature {
using LibRichErrorsV06 for bytes;
// '\x19Ethereum Signed Message:\n32\x00\x00\x00\x00' in a word.
uint256 private constant ETH_SIGN_HASH_PREFIX =
0x19457468657265756d205369676e6564204d6573736167653a0a333200000000;
/// @dev Exclusive upper limit on ECDSA signatures 'R' values.
/// The valid range is given by fig (282) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_R_LIMIT =
uint256(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141);
/// @dev Exclusive upper limit on ECDSA signatures 'S' values.
/// The valid range is given by fig (283) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_S_LIMIT = ECDSA_SIGNATURE_R_LIMIT / 2 + 1;
/// @dev Allowed signature types.
enum SignatureType {
ILLEGAL,
INVALID,
EIP712,
ETHSIGN
}
/// @dev Encoded EC signature.
struct Signature {
// How to validate the signature.
SignatureType signatureType;
// EC Signature data.
uint8 v;
// EC Signature data.
bytes32 r;
// EC Signature data.
bytes32 s;
}
/// @dev Retrieve the signer of a signature.
/// Throws if the signature can't be validated.
/// @param hash The hash that was signed.
/// @param signature The signature.
/// @return recovered The recovered signer address.
function getSignerOfHash(
bytes32 hash,
Signature memory signature
)
internal
pure
returns (address recovered)
{
// Ensure this is a signature type that can be validated against a hash.
_validateHashCompatibleSignature(hash, signature);
if (signature.signatureType == SignatureType.EIP712) {
// Signed using EIP712
recovered = ecrecover(
hash,
signature.v,
signature.r,
signature.s
);
} else if (signature.signatureType == SignatureType.ETHSIGN) {
// Signed using `eth_sign`
// Need to hash `hash` with "\x19Ethereum Signed Message:\n32" prefix
// in packed encoding.
bytes32 ethSignHash;
assembly {
// Use scratch space
mstore(0, ETH_SIGN_HASH_PREFIX) // length of 28 bytes
mstore(28, hash) // length of 32 bytes
ethSignHash := keccak256(0, 60)
}
recovered = ecrecover(
ethSignHash,
signature.v,
signature.r,
signature.s
);
}
// `recovered` can be null if the signature values are out of range.
if (recovered == address(0)) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
}
/// @dev Validates that a signature is compatible with a hash signee.
/// @param hash The hash that was signed.
/// @param signature The signature.
function _validateHashCompatibleSignature(
bytes32 hash,
Signature memory signature
)
private
pure
{
// Ensure the r and s are within malleability limits.
if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT ||
uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT)
{
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
// Always illegal signature.
if (signature.signatureType == SignatureType.ILLEGAL) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL,
hash
).rrevert();
}
// Always invalid.
if (signature.signatureType == SignatureType.INVALID) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID,
hash
).rrevert();
}
// Solidity should check that the signature type is within enum range for us
// when abi-decoding.
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../../errors/LibNativeOrdersRichErrors.sol";
/// @dev A library for common native order operations.
library LibNativeOrder {
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
enum OrderStatus {
INVALID,
FILLABLE,
FILLED,
CANCELLED,
EXPIRED
}
/// @dev A standard OTC or OO limit order.
struct LimitOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
uint128 takerTokenFeeAmount;
address maker;
address taker;
address sender;
address feeRecipient;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An RFQ limit order.
struct RfqOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An OTC limit order.
struct OtcOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
uint256 expiryAndNonce; // [uint64 expiry, uint64 nonceBucket, uint128 nonce]
}
/// @dev Info on a limit or RFQ order.
struct OrderInfo {
bytes32 orderHash;
OrderStatus status;
uint128 takerTokenFilledAmount;
}
/// @dev Info on an OTC order.
struct OtcOrderInfo {
bytes32 orderHash;
OrderStatus status;
}
uint256 private constant UINT_128_MASK = (1 << 128) - 1;
uint256 private constant UINT_64_MASK = (1 << 64) - 1;
uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
// The type hash for limit orders, which is:
// keccak256(abi.encodePacked(
// "LimitOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "uint128 takerTokenFeeAmount,",
// "address maker,",
// "address taker,",
// "address sender,",
// "address feeRecipient,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _LIMIT_ORDER_TYPEHASH =
0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49;
// The type hash for RFQ orders, which is:
// keccak256(abi.encodePacked(
// "RfqOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _RFQ_ORDER_TYPEHASH =
0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9;
// The type hash for OTC orders, which is:
// keccak256(abi.encodePacked(
// "OtcOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "uint256 expiryAndNonce"
// ")"
// ))
uint256 private constant _OTC_ORDER_TYPEHASH =
0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8;
/// @dev Get the struct hash of a limit order.
/// @param order The limit order.
/// @return structHash The struct hash of the order.
function getLimitOrderStructHash(LimitOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.takerTokenFeeAmount,
// order.maker,
// order.taker,
// order.sender,
// order.feeRecipient,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _LIMIT_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.takerTokenFeeAmount;
mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80))))
// order.maker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.taker;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.sender;
mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0))))
// order.feeRecipient;
mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100))))
// order.pool;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
// order.expiry;
mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140))))
// order.salt;
mstore(add(mem, 0x180), mload(add(order, 0x160)))
structHash := keccak256(mem, 0x1A0)
}
}
/// @dev Get the struct hash of a RFQ order.
/// @param order The RFQ order.
/// @return structHash The struct hash of the order.
function getRfqOrderStructHash(RfqOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _RFQ_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.pool;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
// order.expiry;
mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100))))
// order.salt;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
structHash := keccak256(mem, 0x160)
}
}
/// @dev Get the struct hash of an OTC order.
/// @param order The OTC order.
/// @return structHash The struct hash of the order.
function getOtcOrderStructHash(OtcOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.expiryAndNonce,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _OTC_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.expiryAndNonce;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
structHash := keccak256(mem, 0x120)
}
}
/// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`.
/// @param ethProtocolFeePaid How much ETH was paid in protocol fees.
function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid)
internal
{
if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) {
uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid);
(bool success,) = msg
.sender
.call{value: refundAmount}("");
if (!success) {
LibNativeOrdersRichErrors.ProtocolFeeRefundFailed(
msg.sender,
refundAmount
).rrevert();
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
/// @dev Events emitted by NativeOrdersFeature.
interface INativeOrdersEvents {
/// @dev Emitted whenever a `LimitOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param feeRecipient Fee recipient of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param protocolFeePaid How much protocol fee was paid.
/// @param pool The fee pool associated with this order.
event LimitOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address feeRecipient,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
uint128 takerTokenFeeFilledAmount,
uint256 protocolFeePaid,
bytes32 pool
);
/// @dev Emitted whenever an `RfqOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param pool The fee pool associated with this order.
event RfqOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
bytes32 pool
);
/// @dev Emitted whenever a limit or RFQ order is cancelled.
/// @param orderHash The canonical hash of the order.
/// @param maker The order maker.
event OrderCancelled(
bytes32 orderHash,
address maker
);
/// @dev Emitted whenever Limit orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledLimitOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted whenever RFQ orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledRfqOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted when new addresses are allowed or disallowed to fill
/// orders with a given txOrigin.
/// @param origin The address doing the allowing.
/// @param addrs The address being allowed/disallowed.
/// @param allowed Indicates whether the address should be allowed.
event RfqOrderOriginsAllowed(
address origin,
address[] addrs,
bool allowed
);
/// @dev Emitted when new order signers are registered
/// @param maker The maker address that is registering a designated signer.
/// @param signer The address that will sign on behalf of maker.
/// @param allowed Indicates whether the address should be allowed.
event OrderSignerRegistered(
address maker,
address signer,
bool allowed
);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSignatureRichErrors {
enum SignatureValidationErrorCodes {
ALWAYS_INVALID,
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
WRONG_SIGNER,
BAD_SIGNATURE_DATA
}
// solhint-disable func-name-mixedcase
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash,
address signerAddress,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")),
code,
hash,
signerAddress,
signature
);
}
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32)")),
code,
hash
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibSafeMathRichErrorsV06.sol";
library LibSafeMathV06 {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function safeMul128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (a == 0) {
return 0;
}
uint128 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint128 c = a / b;
return c;
}
function safeSub128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
uint128 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a >= b ? a : b;
}
function min128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a < b ? a : b;
}
function safeDowncastToUint128(uint256 a)
internal
pure
returns (uint128)
{
if (a > type(uint128).max) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256DowncastError(
LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128,
a
));
}
return uint128(a);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibNativeOrdersRichErrors {
// solhint-disable func-name-mixedcase
function ProtocolFeeRefundFailed(
address receiver,
uint256 refundAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")),
receiver,
refundAmount
);
}
function OrderNotFillableByOriginError(
bytes32 orderHash,
address txOrigin,
address orderTxOrigin
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")),
orderHash,
txOrigin,
orderTxOrigin
);
}
function OrderNotFillableError(
bytes32 orderHash,
uint8 orderStatus
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")),
orderHash,
orderStatus
);
}
function OrderNotSignedByMakerError(
bytes32 orderHash,
address signer,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")),
orderHash,
signer,
maker
);
}
function OrderNotSignedByTakerError(
bytes32 orderHash,
address signer,
address taker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByTakerError(bytes32,address,address)")),
orderHash,
signer,
taker
);
}
function InvalidSignerError(
address maker,
address signer
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidSignerError(address,address)")),
maker,
signer
);
}
function OrderNotFillableBySenderError(
bytes32 orderHash,
address sender,
address orderSender
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")),
orderHash,
sender,
orderSender
);
}
function OrderNotFillableByTakerError(
bytes32 orderHash,
address taker,
address orderTaker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")),
orderHash,
taker,
orderTaker
);
}
function CancelSaltTooLowError(
uint256 minValidSalt,
uint256 oldMinValidSalt
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")),
minValidSalt,
oldMinValidSalt
);
}
function FillOrKillFailedError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
function OnlyOrderMakerAllowed(
bytes32 orderHash,
address sender,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")),
orderHash,
sender,
maker
);
}
function BatchFillIncompleteError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSafeMathRichErrorsV06 {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IWallet.sol";
contract ZeroExController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line
IWallet public immutable WALLET;
constructor(IWallet wallet) public {
require(address(wallet) != address(0), "INVALID_WALLET");
WALLET = wallet;
}
/// @notice Deposits tokens into WALLET
/// @dev Call to external contract via _approve functions
/// @param data Bytes containing an array of token addresses and token accounts
function deploy(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) = abi.decode(
data,
(address[], uint256[])
);
uint256 tokensLength = tokens.length;
for (uint256 i = 0; i < tokensLength; i++) {
_approve(IERC20(tokens[i]), amounts[i]);
}
WALLET.deposit(tokens, amounts);
}
/// @notice Withdraws tokens from WALLET
/// @param data Bytes containing address and uint256 array
function withdraw(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) = abi.decode(
data,
(address[], uint256[])
);
WALLET.withdraw(tokens, amounts);
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(WALLET));
if(currentAllowance > 0) {
token.safeDecreaseAllowance(address(WALLET), currentAllowance);
}
token.safeIncreaseAllowance(address(WALLET), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IManager.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {AccessControlUpgradeable as AccessControl} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "../interfaces/events/Destinations.sol";
import "../interfaces/events/CycleRolloverEvent.sol";
contract Manager is IManager, Initializable, AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE");
bytes32 public constant MID_CYCLE_ROLE = keccak256("MID_CYCLE_ROLE");
uint256 public currentCycle; // Start block of current cycle
uint256 public currentCycleIndex; // Uint representing current cycle
uint256 public cycleDuration; // Cycle duration in block number
bool public rolloverStarted;
// Bytes32 controller id => controller address
mapping(bytes32 => address) public registeredControllers;
// Cycle index => ipfs rewards hash
mapping(uint256 => string) public override cycleRewardsHashes;
EnumerableSet.AddressSet private pools;
EnumerableSet.Bytes32Set private controllerIds;
// Reentrancy Guard
bool private _entered;
bool public _eventSend;
Destinations public destinations;
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyRollover() {
require(hasRole(ROLLOVER_ROLE, _msgSender()), "NOT_ROLLOVER_ROLE");
_;
}
modifier onlyMidCycle() {
require(hasRole(MID_CYCLE_ROLE, _msgSender()), "NOT_MID_CYCLE_ROLE");
_;
}
modifier nonReentrant() {
require(!_entered, "ReentrancyGuard: reentrant call");
_entered = true;
_;
_entered = false;
}
modifier onEventSend() {
if (_eventSend) {
_;
}
}
function initialize(uint256 _cycleDuration) public initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
cycleDuration = _cycleDuration;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(ADMIN_ROLE, _msgSender());
_setupRole(ROLLOVER_ROLE, _msgSender());
_setupRole(MID_CYCLE_ROLE, _msgSender());
}
function registerController(bytes32 id, address controller) external override onlyAdmin {
require(!controllerIds.contains(id), "CONTROLLER_EXISTS");
registeredControllers[id] = controller;
controllerIds.add(id);
emit ControllerRegistered(id, controller);
}
function unRegisterController(bytes32 id) external override onlyAdmin {
require(controllerIds.contains(id), "INVALID_CONTROLLER");
emit ControllerUnregistered(id, registeredControllers[id]);
delete registeredControllers[id];
controllerIds.remove(id);
}
function registerPool(address pool) external override onlyAdmin {
require(!pools.contains(pool), "POOL_EXISTS");
pools.add(pool);
emit PoolRegistered(pool);
}
function unRegisterPool(address pool) external override onlyAdmin {
require(pools.contains(pool), "INVALID_POOL");
pools.remove(pool);
emit PoolUnregistered(pool);
}
function setCycleDuration(uint256 duration) external override onlyAdmin {
cycleDuration = duration;
emit CycleDurationSet(duration);
}
function getPools() external view override returns (address[] memory) {
address[] memory returnData = new address[](pools.length());
for (uint256 i = 0; i < pools.length(); i++) {
returnData[i] = pools.at(i);
}
return returnData;
}
function getControllers() external view override returns (bytes32[] memory) {
bytes32[] memory returnData = new bytes32[](controllerIds.length());
for (uint256 i = 0; i < controllerIds.length(); i++) {
returnData[i] = controllerIds.at(i);
}
return returnData;
}
function completeRollover(string calldata rewardsIpfsHash) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
_completeRollover(rewardsIpfsHash);
}
/// @notice Used for mid-cycle adjustments
function executeMaintenance(MaintenanceExecution calldata params)
external
override
onlyMidCycle
nonReentrant
{
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
}
function executeRollover(RolloverExecution calldata params) external override onlyRollover nonReentrant {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
// Transfer deployable liquidity out of the pools and into the manager
for (uint256 i = 0; i < params.poolData.length; i++) {
require(pools.contains(params.poolData[i].pool), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolData[i].pool);
IERC20 underlyingToken = pool.underlyer();
underlyingToken.safeTransferFrom(
address(pool),
address(this),
params.poolData[i].amount
);
emit LiquidityMovedToManager(params.poolData[i].pool, params.poolData[i].amount);
}
// Deploy or withdraw liquidity
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
// Transfer recovered liquidity back into the pools; leave no funds in the manager
for (uint256 y = 0; y < params.poolsForWithdraw.length; y++) {
require(pools.contains(params.poolsForWithdraw[y]), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolsForWithdraw[y]);
IERC20 underlyingToken = pool.underlyer();
uint256 managerBalance = underlyingToken.balanceOf(address(this));
// transfer funds back to the pool if there are funds
if (managerBalance > 0) {
underlyingToken.safeTransfer(address(pool), managerBalance);
}
emit LiquidityMovedToPool(params.poolsForWithdraw[y], managerBalance);
}
if (params.complete) {
_completeRollover(params.rewardsIpfsHash);
}
}
function _executeControllerCommand(ControllerTransferData calldata transfer) private {
address controllerAddress = registeredControllers[transfer.controllerId];
require(controllerAddress != address(0), "INVALID_CONTROLLER");
controllerAddress.functionDelegateCall(transfer.data, "CYCLE_STEP_EXECUTE_FAILED");
emit DeploymentStepExecuted(transfer.controllerId, controllerAddress, transfer.data);
}
function startCycleRollover() external override onlyRollover {
rolloverStarted = true;
emit CycleRolloverStarted(block.number);
}
function _completeRollover(string calldata rewardsIpfsHash) private {
currentCycle = block.number;
cycleRewardsHashes[currentCycleIndex] = rewardsIpfsHash;
currentCycleIndex = currentCycleIndex.add(1);
rolloverStarted = false;
bytes32 eventSig = "Cycle Complete";
encodeAndSendData(eventSig);
emit CycleRolloverComplete(block.number);
}
function getCurrentCycle() external view override returns (uint256) {
return currentCycle;
}
function getCycleDuration() external view override returns (uint256) {
return cycleDuration;
}
function getCurrentCycleIndex() external view override returns (uint256) {
return currentCycleIndex;
}
function getRolloverStatus() external view override returns (bool) {
return rolloverStarted;
}
function setDestinations(address _fxStateSender, address _destinationOnL2) external override onlyAdmin {
require(_fxStateSender != address(0), "INVALID_ADDRESS");
require(_destinationOnL2 != address(0), "INVALID_ADDRESS");
destinations.fxStateSender = IFxStateSender(_fxStateSender);
destinations.destinationOnL2 = _destinationOnL2;
emit DestinationsSet(_fxStateSender, _destinationOnL2);
}
function setEventSend(bool _eventSendSet) external override onlyAdmin {
_eventSend = _eventSendSet;
emit EventSendSet(_eventSendSet);
}
function encodeAndSendData(bytes32 _eventSig) private onEventSend {
require(address(destinations.fxStateSender) != address(0), "ADDRESS_NOT_SET");
require(destinations.destinationOnL2 != address(0), "ADDRESS_NOT_SET");
bytes memory data = abi.encode(CycleRolloverEvent({
eventSig: _eventSig,
cycleIndex: currentCycleIndex,
blockNumber: currentCycle
}));
destinations.fxStateSender.sendMessageToChild(destinations.destinationOnL2, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IManager {
// bytes can take on the form of deploying or recovering liquidity
struct ControllerTransferData {
bytes32 controllerId; // controller to target
bytes data; // data the controller will pass
}
struct PoolTransferData {
address pool; // pool to target
uint256 amount; // amount to transfer
}
struct MaintenanceExecution {
ControllerTransferData[] cycleSteps;
}
struct RolloverExecution {
PoolTransferData[] poolData;
ControllerTransferData[] cycleSteps;
address[] poolsForWithdraw; //Pools to target for manager -> pool transfer
bool complete; //Whether to mark the rollover complete
string rewardsIpfsHash;
}
event ControllerRegistered(bytes32 id, address controller);
event ControllerUnregistered(bytes32 id, address controller);
event PoolRegistered(address pool);
event PoolUnregistered(address pool);
event CycleDurationSet(uint256 duration);
event LiquidityMovedToManager(address pool, uint256 amount);
event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data);
event LiquidityMovedToPool(address pool, uint256 amount);
event CycleRolloverStarted(uint256 blockNumber);
event CycleRolloverComplete(uint256 blockNumber);
event DestinationsSet(address destinationOnL1, address destinationOnL2);
event EventSendSet(bool eventSendSet);
/// @notice Registers controller
/// @param id Bytes32 id of controller
/// @param controller Address of controller
function registerController(bytes32 id, address controller) external;
/// @notice Registers pool
/// @param pool Address of pool
function registerPool(address pool) external;
/// @notice Unregisters controller
/// @param id Bytes32 controller id
function unRegisterController(bytes32 id) external;
/// @notice Unregisters pool
/// @param pool Address of pool
function unRegisterPool(address pool) external;
///@notice Gets addresses of all pools registered
///@return Memory array of pool addresses
function getPools() external view returns (address[] memory);
///@notice Gets ids of all controllers registered
///@return Memory array of Bytes32 controller ids
function getControllers() external view returns (bytes32[] memory);
///@notice Allows for owner to set cycle duration
///@param duration Block durtation of cycle
function setCycleDuration(uint256 duration) external;
///@notice Starts cycle rollover
///@dev Sets rolloverStarted state boolean to true
function startCycleRollover() external;
///@notice Allows for controller commands to be executed midcycle
///@param params Contains data for controllers and params
function executeMaintenance(MaintenanceExecution calldata params) external;
///@notice Allows for withdrawals and deposits for pools along with liq deployment
///@param params Contains various data for executing against pools and controllers
function executeRollover(RolloverExecution calldata params) external;
///@notice Completes cycle rollover, publishes rewards hash to ipfs
///@param rewardsIpfsHash rewards hash uploaded to ipfs
function completeRollover(string calldata rewardsIpfsHash) external;
///@notice Gets reward hash by cycle index
///@param index Cycle index to retrieve rewards hash
///@return String memory hash
function cycleRewardsHashes(uint256 index) external view returns (string memory);
///@notice Gets current starting block
///@return uint256 with block number
function getCurrentCycle() external view returns (uint256);
///@notice Gets current cycle index
///@return uint256 current cycle number
function getCurrentCycleIndex() external view returns (uint256);
///@notice Gets current cycle duration
///@return uint256 in block of cycle duration
function getCycleDuration() external view returns (uint256);
///@notice Gets cycle rollover status, true for rolling false for not
///@return Bool representing whether cycle is rolling over or not
function getRolloverStatus() external view returns (bool);
function setDestinations(address destinationOnL1, address destinationOnL2) external;
/// @notice Sets state variable that tells contract if it can send data to EventProxy
/// @param eventSendSet Bool to set state variable to
function setEventSend(bool eventSendSet) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
event DestinationsSet(address fxStateSender, address destinationOnL2);
event EventSendSet(bool eventSendSet);
event WithdrawalRequested(address requestor, uint256 amount);
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount) external;
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (ERC20Upgradeable);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
function setDestinations(address destinationOnL1, address destinationOnL2) external;
/// @notice Sets state variable that tells contract if it can send data to EventProxy
/// @param eventSendSet Bool to set state variable to
function setEventSend(bool eventSendSet) external;
}
// 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// 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 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] = 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;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity >= 0.6.11;
import "../../fxPortal/IFxStateSender.sol";
struct Destinations {
IFxStateSender fxStateSender;
address destinationOnL2;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.11;
struct CycleRolloverEvent {
bytes32 eventSig;
uint256 cycleIndex;
uint256 blockNumber;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// 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
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;
interface IFxStateSender {
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IStaking.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable as ReentrancyGuard} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "../interfaces/events/Destinations.sol";
import "../interfaces/events/BalanceUpdateEvent.sol";
contract Staking is IStaking, Initializable, Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
IERC20 public tokeToken;
IManager public manager;
address public treasury;
uint256 public withheldLiquidity;
//userAddress -> withdrawalInfo
mapping(address => WithdrawalInfo) public requestedWithdrawals;
//userAddress -> -> scheduleIndex -> staking detail
mapping(address => mapping(uint256 => StakingDetails)) public userStakings;
//userAddress -> scheduleIdx[]
mapping(address => uint256[]) public userStakingSchedules;
//Schedule id/index counter
uint256 public nextScheduleIndex;
//scheduleIndex/id -> schedule
mapping(uint256 => StakingSchedule) public schedules;
//scheduleIndex/id[]
EnumerableSet.UintSet private scheduleIdxs;
//Can deposit into a non-public schedule
mapping(address => bool) public override permissionedDepositors;
bool public _eventSend;
Destinations public destinations;
modifier onlyPermissionedDepositors() {
require(_isAllowedPermissionedDeposit(), "CALLER_NOT_PERMISSIONED");
_;
}
modifier onEventSend() {
if(_eventSend) {
_;
}
}
function initialize(
IERC20 _tokeToken,
IManager _manager,
address _treasury
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN");
require(address(_manager) != address(0), "INVALID_MANAGER");
require(_treasury != address(0), "INVALID_TREASURY");
tokeToken = _tokeToken;
manager = _manager;
treasury = _treasury;
//We want to be sure the schedule used for LP staking is first
//because the order in which withdraws happen need to start with LP stakes
_addSchedule(
StakingSchedule({
cliff: 0,
duration: 1,
interval: 1,
setup: true,
isActive: true,
hardStart: 0,
isPublic: true
})
);
}
function addSchedule(StakingSchedule memory schedule) external override onlyOwner {
_addSchedule(schedule);
}
function setPermissionedDepositor(address account, bool canDeposit)
external
override
onlyOwner
{
permissionedDepositors[account] = canDeposit;
}
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs)
external
override
onlyOwner
{
userStakingSchedules[account] = userSchedulesIdxs;
}
function getSchedules()
external
view
override
returns (StakingScheduleInfo[] memory retSchedules)
{
uint256 length = scheduleIdxs.length();
retSchedules = new StakingScheduleInfo[](length);
for (uint256 i = 0; i < length; i++) {
retSchedules[i] = StakingScheduleInfo(
schedules[scheduleIdxs.at(i)],
scheduleIdxs.at(i)
);
}
}
function removeSchedule(uint256 scheduleIndex) external override onlyOwner {
require(scheduleIdxs.contains(scheduleIndex), "INVALID_SCHEDULE");
scheduleIdxs.remove(scheduleIndex);
delete schedules[scheduleIndex];
emit ScheduleRemoved(scheduleIndex);
}
function getStakes(address account)
external
view
override
returns (StakingDetails[] memory stakes)
{
stakes = _getStakes(account);
}
function balanceOf(address account) public view override returns (uint256 value) {
value = 0;
uint256 scheduleCount = userStakingSchedules[account].length;
for (uint256 i = 0; i < scheduleCount; i++) {
uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub(
userStakings[account][userStakingSchedules[account][i]].withdrawn
);
uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed;
if (remaining > slashed) {
value = value.add(remaining.sub(slashed));
}
}
}
function availableForWithdrawal(address account, uint256 scheduleIndex)
external
view
override
returns (uint256)
{
return _availableForWithdrawal(account, scheduleIndex);
}
function unvested(address account, uint256 scheduleIndex)
external
view
override
returns (uint256 value)
{
value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
value = stake.initial.sub(_vested(account, scheduleIndex));
}
function vested(address account, uint256 scheduleIndex)
external
view
override
returns (uint256 value)
{
return _vested(account, scheduleIndex);
}
function deposit(uint256 amount, uint256 scheduleIndex) external override {
_depositFor(msg.sender, amount, scheduleIndex);
}
function depositFor(
address account,
uint256 amount,
uint256 scheduleIndex
) external override {
require(_isAllowedPermissionedDeposit(), "PERMISSIONED_FUNCTION");
_depositFor(account, amount, scheduleIndex);
}
function depositWithSchedule(
address account,
uint256 amount,
StakingSchedule calldata schedule
) external override onlyPermissionedDepositors {
uint256 scheduleIx = nextScheduleIndex;
_addSchedule(schedule);
_depositFor(account, amount, scheduleIx);
}
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 length = stakes.length;
uint256 stakedAvailable = 0;
for (uint256 i = 0; i < length; i++) {
stakedAvailable = stakedAvailable.add(
_availableForWithdrawal(msg.sender, stakes[i].scheduleIx)
);
}
require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE");
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1);
}
bytes32 eventSig = "WithdrawalRequest";
encodeAndSendData(eventSig, msg.sender);
emit WithdrawalRequested(msg.sender, amount);
}
function withdraw(uint256 amount) external override nonReentrant whenNotPaused {
require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE");
require(amount > 0, "NO_WITHDRAWAL");
require(
requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 available = 0;
uint256 length = stakes.length;
uint256 remainingAmount = amount;
uint256 stakedAvailable = 0;
for (uint256 i = 0; i < length && remainingAmount > 0; i++) {
stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx);
available = available.add(stakedAvailable);
if (stakedAvailable < remainingAmount) {
remainingAmount = remainingAmount.sub(stakedAvailable);
stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable);
} else {
stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount);
remainingAmount = 0;
}
userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i];
}
require(remainingAmount == 0, "INSUFFICIENT_AVAILABLE"); //May not need to check this again
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
amount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
bytes32 eventSig = "Withdraw";
encodeAndSendData(eventSig, msg.sender);
withheldLiquidity = withheldLiquidity.sub(amount);
tokeToken.safeTransfer(msg.sender, amount);
emit WithdrawCompleted(msg.sender, amount);
}
function slash(
address account,
uint256 amount,
uint256 scheduleIndex
) external onlyOwner whenNotPaused {
StakingSchedule storage schedule = schedules[scheduleIndex];
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
require(userStake.initial > 0, "NO_VESTING");
uint256 availableToSlash = 0;
uint256 remaining = userStake.initial.sub(userStake.withdrawn);
if (remaining > userStake.slashed) {
availableToSlash = remaining.sub(userStake.slashed);
}
require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE");
userStake.slashed = userStake.slashed.add(amount);
userStakings[account][scheduleIndex] = userStake;
bytes32 eventSig = "Slashed";
encodeAndSendData(eventSig, account);
tokeToken.safeTransfer(treasury, amount);
emit Slashed(account, amount, scheduleIndex);
}
function setScheduleStatus(uint256 scheduleId, bool activeBool) external override onlyOwner {
StakingSchedule storage schedule = schedules[scheduleId];
schedule.isActive = activeBool;
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function setDestinations(address _fxStateSender, address _destinationOnL2) external override onlyOwner {
require(_fxStateSender != address(0), "INVALID_ADDRESS");
require(_destinationOnL2 != address(0), "INVALID_ADDRESS");
destinations.fxStateSender = IFxStateSender(_fxStateSender);
destinations.destinationOnL2 = _destinationOnL2;
emit DestinationsSet(_fxStateSender, _destinationOnL2);
}
function setEventSend(bool _eventSendSet) external override onlyOwner {
_eventSend = _eventSendSet;
emit EventSendSet(_eventSendSet);
}
function _availableForWithdrawal(address account, uint256 scheduleIndex)
private
view
returns (uint256)
{
StakingDetails memory stake = userStakings[account][scheduleIndex];
uint256 vestedWoWithdrawn = _vested(account, scheduleIndex).sub(stake.withdrawn);
if (stake.slashed > vestedWoWithdrawn) return 0;
return vestedWoWithdrawn.sub(stake.slashed);
}
function _depositFor(
address account,
uint256 amount,
uint256 scheduleIndex
) private nonReentrant whenNotPaused {
StakingSchedule memory schedule = schedules[scheduleIndex];
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
require(schedule.isActive, "INACTIVE_SCHEDULE");
require(account != address(0), "INVALID_ADDRESS");
require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
if (userStake.initial == 0) {
userStakingSchedules[account].push(scheduleIndex);
}
userStake.initial = userStake.initial.add(amount);
if (schedule.hardStart > 0) {
userStake.started = schedule.hardStart;
} else {
// solhint-disable-next-line not-rely-on-time
userStake.started = block.timestamp;
}
userStake.scheduleIx = scheduleIndex;
userStakings[account][scheduleIndex] = userStake;
bytes32 eventSig = "Deposit";
encodeAndSendData(eventSig, account);
tokeToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposited(account, amount, scheduleIndex);
}
function _vested(address account, uint256 scheduleIndex) private view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timestamp = block.timestamp;
uint256 value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
StakingSchedule memory schedule = schedules[scheduleIndex];
uint256 cliffTimestamp = stake.started.add(schedule.cliff);
if (cliffTimestamp <= timestamp) {
if (cliffTimestamp.add(schedule.duration) <= timestamp) {
value = stake.initial;
} else {
uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1);
uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div(
schedule.interval
);
value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration);
}
}
return value;
}
function _addSchedule(StakingSchedule memory schedule) private {
require(schedule.duration > 0, "INVALID_DURATION");
require(schedule.interval > 0, "INVALID_INTERVAL");
schedule.setup = true;
uint256 index = nextScheduleIndex;
schedules[index] = schedule;
scheduleIdxs.add(index);
nextScheduleIndex = nextScheduleIndex.add(1);
emit ScheduleAdded(
index,
schedule.cliff,
schedule.duration,
schedule.interval,
schedule.setup,
schedule.isActive,
schedule.hardStart
);
}
function _getStakes(address account) private view returns (StakingDetails[] memory stakes) {
uint256 stakeCnt = userStakingSchedules[account].length;
stakes = new StakingDetails[](stakeCnt);
for (uint256 i = 0; i < stakeCnt; i++) {
stakes[i] = userStakings[account][userStakingSchedules[account][i]];
}
}
function _isAllowedPermissionedDeposit() private view returns (bool) {
return permissionedDepositors[msg.sender] || msg.sender == owner();
}
function encodeAndSendData(bytes32 _eventSig, address _user) private onEventSend {
require(address(destinations.fxStateSender) != address(0), "ADDRESS_NOT_SET");
require(destinations.destinationOnL2 != address(0), "ADDRESS_NOT_SET");
uint256 userBalance = balanceOf(_user).sub(requestedWithdrawals[_user].amount);
bytes memory data = abi.encode(BalanceUpdateEvent({
eventSig: _eventSig,
account: _user,
token: address(tokeToken),
amount: userBalance
}));
destinations.fxStateSender.sendMessageToChild(destinations.destinationOnL2, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IStaking {
struct StakingSchedule {
uint256 cliff; // Duration in seconds before staking starts
uint256 duration; // Seconds it takes for entire amount to stake
uint256 interval; // Seconds it takes for a chunk to stake
bool setup; //Just so we know its there
bool isActive; //Whether we can setup new stakes with the schedule
uint256 hardStart; //Stakings will always start at this timestamp if set
bool isPublic; //Schedule can be written to by any account
}
struct StakingScheduleInfo {
StakingSchedule schedule;
uint256 index;
}
struct StakingDetails {
uint256 initial; //Initial amount of asset when stake was created, total amount to be staked before slashing
uint256 withdrawn; //Amount that was staked and subsequently withdrawn
uint256 slashed; //Amount that has been slashed
uint256 started; //Timestamp at which the stake started
uint256 scheduleIx;
}
struct WithdrawalInfo {
uint256 minCycleIndex;
uint256 amount;
}
event ScheduleAdded(uint256 scheduleIndex, uint256 cliff, uint256 duration, uint256 interval, bool setup, bool isActive, uint256 hardStart);
event ScheduleRemoved(uint256 scheduleIndex);
event WithdrawalRequested(address account, uint256 amount);
event WithdrawCompleted(address account, uint256 amount);
event Deposited(address account, uint256 amount, uint256 scheduleIx);
event Slashed(address account, uint256 amount, uint256 scheduleIx);
event DestinationsSet(address fxStateSender, address destinationOnL2);
event EventSendSet(bool eventSendSet);
///@notice Allows for checking of user address in permissionedDepositors mapping
///@param account Address of account being checked
///@return Boolean, true if address exists in mapping
function permissionedDepositors(address account) external returns (bool);
///@notice Allows owner to set a multitude of schedules that an address has access to
///@param account User address
///@param userSchedulesIdxs Array of schedule indexes
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external;
///@notice Allows owner to add schedule
///@param schedule A StakingSchedule struct that contains all info needed to make a schedule
function addSchedule(StakingSchedule memory schedule) external;
///@notice Gets all info on all schedules
///@return retSchedules An array of StakingScheduleInfo struct
function getSchedules() external view returns (StakingScheduleInfo[] memory retSchedules);
///@notice Allows owner to set a permissioned depositor
///@param account User address
///@param canDeposit Boolean representing whether user can deposit
function setPermissionedDepositor(address account, bool canDeposit) external;
///@notice Allows owner to remove a schedule by schedule Index
///@param scheduleIndex A uint256 representing a schedule
function removeSchedule(uint256 scheduleIndex) external;
///@notice Allows a user to get the stakes of an account
///@param account Address that is being checked for stakes
///@return stakes StakingDetails array containing info about account's stakes
function getStakes(address account) external view returns(StakingDetails[] memory stakes);
///@notice Gets total value staked for an address across all schedules
///@param account Address for which total stake is being calculated
///@return value uint256 total of account
function balanceOf(address account) external view returns(uint256 value);
///@notice Returns amount available to withdraw for an account and schedule Index
///@param account Address that is being checked for withdrawals
///@param scheduleIndex Index of schedule that is being checked for withdrawals
function availableForWithdrawal(address account, uint256 scheduleIndex) external view returns (uint256);
///@notice Returns unvested amount for certain address and schedule index
///@param account Address being checked for unvested amount
///@param scheduleIndex Schedule index being checked for unvested amount
///@return value Uint256 representing unvested amount
function unvested(address account, uint256 scheduleIndex) external view returns(uint256 value);
///@notice Returns vested amount for address and schedule index
///@param account Address being checked for vested amount
///@param scheduleIndex Schedule index being checked for vested amount
///@return value Uint256 vested
function vested(address account, uint256 scheduleIndex) external view returns(uint256 value);
///@notice Allows user to deposit token to specific vesting / staking schedule
///@param amount Uint256 amount to be deposited
///@param scheduleIndex Uint256 representing schedule to user
function deposit(uint256 amount, uint256 scheduleIndex) external;
///@notice Allows account to deposit on behalf of other account
///@param account Account to be deposited for
///@param amount Amount to be deposited
///@param scheduleIndex Index of schedule to be used for deposit
function depositFor(address account, uint256 amount, uint256 scheduleIndex) external;
///@notice Allows permissioned depositors to deposit into custom schedule
///@param account Address of account being deposited for
///@param amount Uint256 amount being deposited
///@param schedule StakingSchedule struct containing details needed for new schedule
function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external;
///@notice User can request withdrawal from staking contract at end of cycle
///@notice Performs checks to make sure amount <= amount available
///@param amount Amount to withdraw
function requestWithdrawal(uint256 amount) external;
///@notice Allows for withdrawal after successful withdraw request and proper amount of cycles passed
///@param amount Amount to withdraw
function withdraw(uint256 amount) external;
function setScheduleStatus(uint256 scheduleIndex, bool activeBoolean) external;
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
function setDestinations(address destinationOnL1, address destinationOnL2) external;
/// @notice Sets state variable that tells contract if it can send data to EventProxy
/// @param eventSendSet Bool to set state variable to
function setEventSend(bool eventSendSet) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// 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.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/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 initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// 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.11;
struct BalanceUpdateEvent {
bytes32 eventSig;
address account;
address token;
uint256 amount;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../interfaces/events/BalanceUpdateEvent.sol";
import "../interfaces/events/Destinations.sol";
import "../fxPortal/IFxStateSender.sol";
contract Pool is ILiquidityPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public override underlyer; // Underlying ERC20 token
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
// NonReentrant
bool private _entered;
bool public _eventSend;
Destinations public destinations;
modifier nonReentrant() {
require(!_entered, "ReentrancyGuard: reentrant call");
_entered = true;
_;
_entered = false;
}
modifier onEventSend() {
if(_eventSend) {
_;
}
}
function initialize(
ERC20 _underlyer,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
require(address(_underlyer) != address(0), "ZERO_ADDRESS");
require(address(_manager) != address(0), "ZERO_ADDRESS");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
underlyer = _underlyer;
manager = _manager;
}
///@notice Gets decimals of underlyer so that tAsset decimals will match
function decimals() public view override returns (uint8) {
return underlyer.decimals();
}
function deposit(uint256 amount) external override whenNotPaused {
_deposit(msg.sender, msg.sender, amount);
}
function depositFor(address account, uint256 amount) external override whenNotPaused {
_deposit(msg.sender, account, amount);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
/// @dev TODO Update rewardsContract with proper accounting
function withdraw(uint256 requestedAmount) external override whenNotPaused nonReentrant {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(underlyer.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
// Checks for manager cycle and if user is allowed to withdraw based on their minimum withdrawal cycle
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
// If full amount withdrawn delete from mapping
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
underlyer.safeTransfer(msg.sender, requestedAmount);
bytes32 eventSig = "Withdraw";
encodeAndSendData(eventSig, msg.sender);
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
//adjust withheld liquidity by removing the original withheld amount and adding the new amount
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) { // If manger is currently rolling over add two to min withdrawal cycle
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else { // If manager is not rolling over add one to minimum withdrawal cycle
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
emit WithdrawalRequested(msg.sender, amount);
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
//reduce requested withdraw amount by transferred amount;
uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
//subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount)
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[sender].amount.sub(newRequestedWithdrawl)
);
//update the requested withdraw for user
requestedWithdrawals[sender].amount = newRequestedWithdrawl;
//if the withdraw request is 0, empty it out
if (requestedWithdrawals[sender].amount == 0) {
delete requestedWithdrawals[sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = underlyer.allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
underlyer.safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
underlyer.safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount)
public
override
whenNotPaused
returns (bool)
{
preTransferAdjustWithheldLiquidity(msg.sender, amount);
(bool success) = super.transfer(recipient, amount);
bytes32 eventSig = "Transfer";
encodeAndSendData(eventSig, msg.sender);
encodeAndSendData(eventSig, recipient);
return success;
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override whenNotPaused returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
(bool success) = super.transferFrom(sender, recipient, amount);
bytes32 eventSig = "Transfer";
encodeAndSendData(eventSig, sender);
encodeAndSendData(eventSig, recipient);
return success;
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function setDestinations(address _fxStateSender, address _destinationOnL2) external override onlyOwner {
require(_fxStateSender != address(0), "INVALID_ADDRESS");
require(_destinationOnL2 != address(0), "INVALID_ADDRESS");
destinations.fxStateSender = IFxStateSender(_fxStateSender);
destinations.destinationOnL2 = _destinationOnL2;
emit DestinationsSet(_fxStateSender, _destinationOnL2);
}
function setEventSend(bool _eventSendSet) external override onlyOwner {
_eventSend = _eventSendSet;
emit EventSendSet(_eventSendSet);
}
function _deposit(
address fromAccount,
address toAccount,
uint256 amount
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
_mint(toAccount, amount);
underlyer.safeTransferFrom(fromAccount, address(this), amount);
bytes32 eventSig = "Deposit";
encodeAndSendData(eventSig, toAccount);
}
function encodeAndSendData(bytes32 _eventSig, address _user) private onEventSend {
require(address(destinations.fxStateSender) != address(0), "ADDRESS_NOT_SET");
require(destinations.destinationOnL2 != address(0), "ADDRESS_NOT_SET");
uint256 userBalance = balanceOf(_user);
bytes memory data = abi.encode(BalanceUpdateEvent({
eventSig: _eventSig,
account: _user,
token: address(this),
amount: userBalance
}));
destinations.fxStateSender.sendMessageToChild(destinations.destinationOnL2, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ILiquidityEthPool.sol";
import "../interfaces/IManager.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {AddressUpgradeable as Address} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../interfaces/events/BalanceUpdateEvent.sol";
import "../interfaces/events/Destinations.sol";
contract EthPool is ILiquidityEthPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
/// @dev TODO: Hardcode addresses, make immuatable, remove from initializer
IWETH public override weth;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
// NonReentrant
bool private _entered;
bool public _eventSend;
Destinations public destinations;
modifier nonReentrant() {
require(!_entered, "ReentrancyGuard: reentrant call");
_entered = true;
_;
_entered = false;
}
modifier onEventSend() {
if (_eventSend) {
_;
}
}
/// @dev necessary to receive ETH
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function initialize(
IWETH _weth,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
require(address(_weth) != address(0), "ZERO_ADDRESS");
require(address(_manager) != address(0), "ZERO_ADDRESS");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
weth = _weth;
manager = _manager;
withheldLiquidity = 0;
}
function deposit(uint256 amount) external payable override whenNotPaused {
_deposit(msg.sender, msg.sender, amount, msg.value);
}
function depositFor(address account, uint256 amount) external payable override whenNotPaused {
_deposit(msg.sender, account, amount, msg.value);
}
function underlyer() external view override returns (address) {
return address(weth);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
function withdraw(uint256 requestedAmount, bool asEth) external override whenNotPaused nonReentrant {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(weth.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
// Delete if all assets withdrawn
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
bytes32 eventSig = "Withdraw";
encodeAndSendData(eventSig, msg.sender);
if (asEth) { // Convert to eth
weth.withdraw(requestedAmount);
msg.sender.sendValue(requestedAmount);
} else { // Send as WETH
IERC20(weth).safeTransfer(msg.sender, requestedAmount);
}
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
//adjust withheld liquidity by removing the original withheld amount and adding the new amount
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) { // If manager is in the middle of a cycle rollover, add two cycles
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else { // If the manager is not in the middle of a rollover, add one cycle
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
emit WithdrawalRequested(msg.sender, amount);
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
//reduce requested withdraw amount by transferred amount;
uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
//subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount)
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[sender].amount.sub(newRequestedWithdrawl)
);
//update the requested withdraw for user
requestedWithdrawals[sender].amount = newRequestedWithdrawl;
//if the withdraw request is 0, empty it out
if (requestedWithdrawals[sender].amount == 0) {
delete requestedWithdrawals[sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = IERC20(weth).allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
IERC20(weth).safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
IERC20(weth).safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount) public override returns (bool) {
preTransferAdjustWithheldLiquidity(msg.sender, amount);
(bool success) = super.transfer(recipient, amount);
bytes32 eventSig = "Transfer";
encodeAndSendData(eventSig, msg.sender);
encodeAndSendData(eventSig, recipient);
return success;
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
(bool success) = super.transferFrom(sender, recipient, amount);
bytes32 eventSig = "Transfer";
encodeAndSendData(eventSig, sender);
encodeAndSendData(eventSig, recipient);
return success;
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function setDestinations(address _fxStateSender, address _destinationOnL2) external override onlyOwner {
require(_fxStateSender != address(0), "INVALID_ADDRESS");
require(_destinationOnL2 != address(0), "INVALID_ADDRESS");
destinations.fxStateSender = IFxStateSender(_fxStateSender);
destinations.destinationOnL2 = _destinationOnL2;
emit DestinationsSet(_fxStateSender, _destinationOnL2);
}
function setEventSend(bool _eventSendSet) external override onlyOwner {
_eventSend = _eventSendSet;
emit EventSendSet(_eventSendSet);
}
function _deposit(
address fromAccount,
address toAccount,
uint256 amount,
uint256 msgValue
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
_mint(toAccount, amount);
if (msgValue > 0) { // If ether get weth
require(msgValue == amount, "AMT_VALUE_MISMATCH");
weth.deposit{value: amount}();
} else { // Else go ahead and transfer weth from account to pool
IERC20(weth).safeTransferFrom(fromAccount, address(this), amount);
}
bytes32 eventSig = "Deposit";
encodeAndSendData(eventSig, toAccount);
}
function encodeAndSendData(bytes32 _eventSig, address _user) private onEventSend {
require(address(destinations.fxStateSender) != address(0), "ADDRESS_NOT_SET");
require(destinations.destinationOnL2 != address(0), "ADDRESS_NOT_SET");
uint256 userBalance = balanceOf(_user);
bytes memory data = abi.encode(BalanceUpdateEvent({
eventSig: _eventSig,
account: _user,
token: address(this),
amount: userBalance
}));
destinations.fxStateSender.sendMessageToChild(destinations.destinationOnL2, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/IWETH.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityEthPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
event DestinationsSet(address destinationOnL1, address destinationOnL2);
event EventSendSet(bool eventSendSet);
event WithdrawalRequested(address requestor, uint256 amount);
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external payable;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external payable;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount, bool asEth) external;
/// @return Reference to the underlying ERC-20 contract
function weth() external view returns (IWETH);
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (address);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
function setDestinations(address destinationOnL1, address destinationOnL2) external;
/// @notice Sets state variable that tells contract if it can send data to EventProxy
/// @param eventSendSet Bool to set state variable to
function setEventSend(bool eventSendSet) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWETH is IERC20Upgradeable {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IDefiRound.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract DefiRound is IDefiRound, Ownable {
using SafeMath for uint256;
using SafeCast for int256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.AddressSet;
// solhint-disable-next-line
address public immutable WETH;
address public override immutable treasury;
OversubscriptionRate public overSubscriptionRate;
mapping(address => uint256) public override totalSupply;
// account -> accountData
mapping(address => AccountData) private accountData;
mapping(address => RateData) private tokenRates;
//Token -> oracle, genesis
mapping(address => SupportedTokenData) private tokenSettings;
EnumerableSet.AddressSet private supportedTokens;
EnumerableSet.AddressSet private configuredTokenRates;
STAGES public override currentStage;
WhitelistSettings public whitelistSettings;
uint256 public lastLookExpiration = type(uint256).max;
uint256 private immutable maxTotalValue;
bool private stage1Locked;
constructor(
// solhint-disable-next-line
address _WETH,
address _treasury,
uint256 _maxTotalValue
) public {
require(_WETH != address(0), "INVALID_WETH");
require(_treasury != address(0), "INVALID_TREASURY");
require(_maxTotalValue > 0, "INVALID_MAXTOTAL");
WETH = _WETH;
treasury = _treasury;
currentStage = STAGES.STAGE_1;
maxTotalValue = _maxTotalValue;
}
function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override {
require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED");
require(!stage1Locked, "DEPOSITS_LOCKED");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
// Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20
if (token == WETH && msg.value > 0) {
require(tokenAmount == msg.value, "INVALID_MSG_VALUE");
IWETH(WETH).deposit{value: tokenAmount}();
} else {
require(msg.value == 0, "NO_ETH");
}
AccountData storage tokenAccountData = accountData[msg.sender];
if (tokenAccountData.token == address(0)) {
tokenAccountData.token = token;
}
require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS");
tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add(tokenAmount);
tokenAccountData.currentBalance = tokenAccountData.currentBalance.add(tokenAmount);
require(tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED");
// No need to transfer from msg.sender since is ETH was converted to WETH
if (!(token == WETH && msg.value > 0)) {
IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);
}
if(_totalValue() > maxTotalValue) {
stage1Locked = true;
}
emit Deposited(msg.sender, tokenInfo);
}
// solhint-disable-next-line no-empty-blocks
receive() external payable
{
require(msg.sender == WETH);
}
function withdraw(TokenData calldata tokenInfo, bool asETH) external override {
require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED");
require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED");
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
AccountData storage tokenAccountData = accountData[msg.sender];
require(token == tokenAccountData.token, "INVALID_TOKEN");
tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub(tokenAmount);
// set the data back in the mapping, otherwise updates are not saved
accountData[msg.sender] = tokenAccountData;
// Don't transfer WETH, WETH is converted to ETH and sent to the recipient
if (token == WETH && asETH) {
IWETH(WETH).withdraw(tokenAmount);
msg.sender.sendValue(tokenAmount);
} else {
IERC20(token).safeTransfer(msg.sender, tokenAmount);
}
emit Withdrawn(msg.sender, tokenInfo, asETH);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport)
external
override
onlyOwner
{
uint256 tokensLength = tokensToSupport.length;
for (uint256 i = 0; i < tokensLength; i++) {
SupportedTokenData memory data = tokensToSupport[i];
require(supportedTokens.add(data.token), "TOKEN_EXISTS");
tokenSettings[data.token] = data;
}
emit SupportedTokensAdded(tokensToSupport);
}
function getSupportedTokens() external view override returns (address[] memory tokens) {
uint256 tokensLength = supportedTokens.length();
tokens = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
tokens[i] = supportedTokens.at(i);
}
}
function publishRates(RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration) external override onlyOwner {
// check rates havent been published before
require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET");
require(lastLookDuration > 0, "INVALID_DURATION");
require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR");
require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR");
uint256 ratesLength = ratesData.length;
for (uint256 i = 0; i < ratesLength; i++) {
RateData memory data = ratesData[i];
require(data.numerator > 0, "INVALID_NUMERATOR");
require(data.denominator > 0, "INVALID_DENOMINATOR");
require(tokenRates[data.token].token == address(0), "RATE_ALREADY_SET");
require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED");
tokenRates[data.token] = data;
}
require(configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE");
// Stage only moves forward when prices are published
currentStage = STAGES.STAGE_2;
lastLookExpiration = block.number + lastLookDuration;
overSubscriptionRate = oversubRate;
emit RatesPublished(ratesData);
}
function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) {
uint256 tokensLength = tokens.length;
rates = new RateData[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
rates[i] = tokenRates[tokens[i]];
}
}
function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) {
uint256 tokenDecimals = ERC20(token).decimals();
(, int256 tokenRate, , , ) = AggregatorV3Interface(tokenSettings[token].oracle).latestRoundData();
uint256 rate = tokenRate.toUint256();
value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8
}
function totalValue() external view override returns (uint256) {
return _totalValue();
}
function _totalValue() internal view returns (uint256 value) {
uint256 tokensLength = supportedTokens.length();
for (uint256 i = 0; i < tokensLength; i++) {
address token = supportedTokens.at(i);
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
value = value.add(getTokenValue(token, tokenBalance));
}
}
function accountBalance(address account) external view override returns (uint256 value) {
uint256 tokenBalance = accountData[account].currentBalance;
value = value.add(getTokenValue(accountData[account].token, tokenBalance));
}
function finalizeAssets(bool depositToGenesis) external override {
require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL");
AccountData storage data = accountData[msg.sender];
address token = data.token;
require(token != address(0), "NO_DATA");
( , uint256 ineffective, ) = _getRateAdjustedAmounts(data.currentBalance, token);
require(ineffective > 0, "NOTHING_TO_MOVE");
// zero out balance
data.currentBalance = 0;
accountData[msg.sender] = data;
if (depositToGenesis) {
address pool = tokenSettings[token].genesis;
uint256 currentAllowance = IERC20(token).allowance(address(this), pool);
if (currentAllowance < ineffective) {
IERC20(token).safeIncreaseAllowance(pool, ineffective.sub(currentAllowance));
}
ILiquidityPool(pool).depositFor(msg.sender, ineffective);
emit GenesisTransfer(msg.sender, ineffective);
} else {
// transfer ineffectiveTokenBalance back to user
IERC20(token).safeTransfer(msg.sender, ineffective);
}
emit AssetsFinalized(msg.sender, token, ineffective);
}
function getGenesisPools(address[] calldata tokens)
external
view
override
returns (address[] memory genesisAddresses)
{
uint256 tokensLength = tokens.length;
genesisAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis;
}
}
function getTokenOracles(address[] calldata tokens)
external
view
override
returns (address[] memory oracleAddresses)
{
uint256 tokensLength = tokens.length;
oracleAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
oracleAddresses[i] = tokenSettings[tokens[i]].oracle;
}
}
function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) {
uint256 supportedTokensLength = supportedTokens.length();
data = new AccountDataDetails[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
AccountData memory accountTokenInfo = accountData[account];
if (currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0)) {
(uint256 effective, uint256 ineffective, uint256 actual) = _getRateAdjustedAmounts(accountTokenInfo.currentBalance, token);
AccountDataDetails memory details = AccountDataDetails(
token,
accountTokenInfo.initialDeposit,
accountTokenInfo.currentBalance,
effective,
ineffective,
actual
);
data[i] = details;
} else {
data[i] = AccountDataDetails(token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0);
}
}
}
function transferToTreasury() external override onlyOwner {
require(_isLastLookComplete(), "CURRENT_STAGE_INVALID");
require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE");
uint256 supportedTokensLength = supportedTokens.length();
TokenData[] memory tokens = new TokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = _getRateAdjustedAmounts(balance, token);
tokens[i].token = token;
tokens[i].amount = effective;
IERC20(token).safeTransfer(treasury, effective);
}
currentStage = STAGES.STAGE_3;
emit TreasuryTransfer(tokens);
}
function getRateAdjustedAmounts(uint256 balance, address token) external override view returns (uint256,uint256,uint256) {
return _getRateAdjustedAmounts(balance, token);
}
function getMaxTotalValue() external view override returns (uint256) {
return maxTotalValue;
}
function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns (uint256,uint256,uint256) {
require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED");
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(overSubscriptionRate.overNumerator).div(overSubscriptionRate.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(overSubscriptionRate.overDenominator.sub(overSubscriptionRate.overNumerator))
.div(overSubscriptionRate.overDenominator);
uint256 actualReceived =
effectiveTokenBalance.mul(rateInfo.denominator).div(rateInfo.numerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived);
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
function _isLastLookComplete() internal view returns (bool) {
return block.number >= lastLookExpiration;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IDefiRound {
enum STAGES {STAGE_1, STAGE_2, STAGE_3}
struct AccountData {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
}
struct AccountDataDetails {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
uint256 effectiveAmt; //Amount deposited that will be used towards TOKE
uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming
uint256 actualTokeReceived; //Amount of TOKE that will be received
}
struct TokenData {
address token;
uint256 amount;
}
struct SupportedTokenData {
address token;
address oracle;
address genesis;
uint256 maxLimit;
}
struct RateData {
address token;
uint256 numerator;
uint256 denominator;
}
struct OversubscriptionRate {
uint256 overNumerator;
uint256 overDenominator;
}
event Deposited(address depositor, TokenData tokenInfo);
event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH);
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event RatesPublished(RateData[] ratesData);
event GenesisTransfer(address user, uint256 amountTransferred);
event AssetsFinalized(address claimer, address token, uint256 assetsMoved);
event WhitelistConfigured(WhitelistSettings settings);
event TreasuryTransfer(TokenData[] tokens);
struct TokenValues {
uint256 effectiveTokenValue;
uint256 ineffectiveTokenValue;
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings calldata settings) external;
/// @notice returns the current stage the contract is in
/// @return stage the current stage the round contract is in
function currentStage() external returns (STAGES stage);
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable;
/// @notice total value held in the entire contract amongst all the assets
/// @return value the value of all assets held
function totalValue() external view returns (uint256 value);
/// @notice Current Max Total Value
/// @return value the max total value
function getMaxTotalValue() external view returns (uint256 value);
/// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go
/// @return treasuryAddress address of the treasury
function treasury() external returns (address treasuryAddress);
/// @notice the total supply held for a given token
/// @param token the token to get the supply for
/// @return amount the total supply for a given token
function totalSupply(address token) external returns (uint256 amount);
/// @notice withdraws tokens from the round contract. only callable when round 2 starts
/// @param tokenData an array of token structs
/// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH
function withdraw(TokenData calldata tokenData, bool asEth) external;
// /// @notice adds tokens to support
// /// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external;
// /// @notice returns which tokens can be deposited
// /// @return tokens tokens that are supported for deposit
function getSupportedTokens() external view returns (address[] calldata tokens);
/// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD
/// @param tokens an array of tokens
/// @return oracleAddresses the an array of oracles corresponding to supported tokens
function getTokenOracles(address[] calldata tokens)
external
view
returns (address[] calldata oracleAddresses);
/// @notice publishes rates for the tokens. Rates are always relative to 1 TOKE. Can only be called once within Stage 1
// prices can be published at any time
/// @param ratesData an array of rate info structs
function publishRates(
RateData[] calldata ratesData,
OversubscriptionRate memory overSubRate,
uint256 lastLookDuration
) external;
/// @notice return the published rates for the tokens
/// @param tokens an array of tokens to get rates for
/// @return rates an array of rates for the provided tokens
function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates);
/// @notice determines the account value in USD amongst all the assets the user is invovled in
/// @param account the account to look up
/// @return value the value of the account in USD
function accountBalance(address account) external view returns (uint256 value);
/// @notice Moves excess assets to private farming or refunds them
/// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of TOKE is claimed
/// @param depositToGenesis applies only if oversubscribedMultiplier < 1;
/// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user
function finalizeAssets(bool depositToGenesis) external;
//// @notice returns what gensis pool a supported token is mapped to
/// @param tokens array of addresses of supported tokens
/// @return genesisAddresses array of genesis pools corresponding to supported tokens
function getGenesisPools(address[] calldata tokens)
external
view
returns (address[] memory genesisAddresses);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account)
external
view
returns (AccountDataDetails[] calldata data);
/// @notice Allows the owner to transfer all swapped assets to the treasury
/// @dev only callable by owner and if last look period is complete
function transferToTreasury() external;
/// @notice Given a balance, calculates how the the amount will be allocated between TOKE and Farming
/// @dev Only allowed at stage 3
/// @param balance balance to divy up
/// @param token token to pull the rates for
function getRateAdjustedAmounts(uint256 balance, address token)
external
view
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ICoreEvent.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract CoreEvent is Ownable, ICoreEvent {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
// Contains start block and duration
DurationInfo public durationInfo;
address public immutable treasuryAddress;
EnumerableSet.AddressSet private supportedTokenAddresses;
// token address -> SupportedTokenData
mapping(address => SupportedTokenData) public supportedTokens;
// user -> token -> AccountData
mapping(address => mapping(address => AccountData)) public accountData;
mapping(address => RateData) public tokenRates;
WhitelistSettings public whitelistSettings;
bool public stage1Locked;
modifier hasEnded() {
require(_hasEnded(), "TOO_EARLY");
_;
}
constructor(
address treasury,
SupportedTokenData[] memory tokensToSupport
) public {
treasuryAddress = treasury;
addSupportedTokens(tokensToSupport);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function setDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock == 0, "ALREADY_STARTED");
durationInfo.startingBlock = block.number;
durationInfo.blockDuration = _blockDuration;
emit DurationSet(durationInfo);
}
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) public override onlyOwner {
require (tokensToSupport.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokensToSupport.length; i++) {
require(
!supportedTokenAddresses.contains(tokensToSupport[i].token),
"DUPLICATE_TOKEN"
);
require(tokensToSupport[i].token != address(0), "ZERO_ADDRESS");
require(!tokensToSupport[i].systemFinalized, "FINALIZED_MUST_BE_FALSE");
supportedTokenAddresses.add(tokensToSupport[i].token);
supportedTokens[tokensToSupport[i].token] = tokensToSupport[i];
}
emit SupportedTokensAdded(tokensToSupport);
}
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external override {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "0_BALANCE");
address token = tokenData[i].token;
require(supportedTokenAddresses.contains(token), "NOT_SUPPORTED");
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
/// Check that total user deposits do not exceed token limit
require(
data.depositedBalance.add(amount) <= supportedTokens[token].maxUserLimit,
"OVER_LIMIT"
);
data.depositedBalance = data.depositedBalance.add(amount);
data.token = token;
erc20Token.safeTransferFrom(msg.sender, address(this), amount);
}
emit Deposited(msg.sender, tokenData);
}
function withdraw(TokenData[] calldata tokenData) external override {
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "ZERO_BALANCE");
address token = tokenData[i].token;
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(data.token != address(0), "ZERO_ADDRESS");
require(amount <= data.depositedBalance, "INSUFFICIENT_FUNDS");
data.depositedBalance = data.depositedBalance.sub(amount);
if (data.depositedBalance == 0) {
delete accountData[msg.sender][token];
}
erc20Token.safeTransfer(msg.sender, amount);
}
emit Withdrawn(msg.sender, tokenData);
}
function increaseDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(_blockDuration > durationInfo.blockDuration, "INCREASE_ONLY");
require(!stage1Locked, "STAGE1_LOCKED");
durationInfo.blockDuration = _blockDuration;
emit DurationIncreased(durationInfo);
}
function setRates(RateData[] calldata rates) external override onlyOwner hasEnded {
//Rates are settable multiple times, but only until they are finalized.
//They are set to finalized by either performing the transferToTreasury
//Or, by marking them as no-swap tokens
//Users cannot begin their next set of actions before a token finalized.
uint256 length = rates.length;
for (uint256 i = 0; i < length; i++) {
RateData memory data = rates[i];
require(supportedTokenAddresses.contains(data.token), "UNSUPPORTED_ADDRESS");
require(!supportedTokens[data.token].systemFinalized, "ALREADY_FINALIZED");
if (data.tokeNumerator > 0) {
//We are allowing an address(0) pool, it means it was a winning reactor
//but there wasn't enough to enable private farming
require(data.tokeDenominator > 0, "INVALID_TOKE_DENOMINATOR");
require(data.overNumerator > 0, "INVALID_OVER_NUMERATOR");
require(data.overDenominator > 0, "INVALID_OVER_DENOMINATOR");
tokenRates[data.token] = data;
} else {
delete tokenRates[data.token];
}
}
stage1Locked = true;
emit RatesPublished(rates);
}
function transferToTreasury(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
TokenData[] memory transfers = new TokenData[](length);
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(tokenRates[token].tokeNumerator > 0, "NO_SWAP_TOKEN");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = getRateAdjustedAmounts(balance, token);
transfers[i].token = token;
transfers[i].amount = effective;
supportedTokens[token].systemFinalized = true;
IERC20(token).safeTransfer(treasuryAddress, effective);
}
emit TreasuryTransfer(transfers);
}
function setNoSwap(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(supportedTokenAddresses.contains(token), "UNSUPPORTED_ADDRESS");
require(tokenRates[token].tokeNumerator == 0, "ALREADY_SET_TO_SWAP");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
supportedTokens[token].systemFinalized = true;
}
stage1Locked = true;
emit SetNoSwap(tokens);
}
function finalize(TokenFarming[] calldata tokens) external override hasEnded {
require(tokens.length > 0, "NO_TOKENS");
uint256 length = tokens.length;
FinalizedAccountData[] memory results = new FinalizedAccountData[](length);
for(uint256 i = 0; i < length; i++) {
TokenFarming calldata farm = tokens[i];
AccountData storage account = accountData[msg.sender][farm.token];
require(!account.finalized, "ALREADY_FINALIZED");
require(farm.token != address(0), "ZERO_ADDRESS");
require(supportedTokens[farm.token].systemFinalized, "NOT_SYSTEM_FINALIZED");
require(account.depositedBalance > 0, "INSUFFICIENT_FUNDS");
RateData storage rate = tokenRates[farm.token];
uint256 amtToTransfer = 0;
if (rate.tokeNumerator > 0) {
//We have set a rate, which means its a winning reactor
//which means only the ineffective amount, the amount
//not spent on TOKE, can leave the contract.
//Leaving to either the farm or back to the user
//In the event there is no farming, an oversubscription rate of 1/1
//will be provided for the token. That will ensure the ineffective
//amount is 0 and caught by the below require() as only assets with
//an oversubscription can be moved
(, uint256 ineffectiveAmt, ) = getRateAdjustedAmounts(account.depositedBalance, farm.token);
amtToTransfer = ineffectiveAmt;
} else {
amtToTransfer = account.depositedBalance;
}
require(amtToTransfer > 0, "NOTHING_TO_MOVE");
account.finalized = true;
if (farm.sendToFarming) {
require(rate.pool != address(0), "NO_FARMING");
uint256 currentAllowance = IERC20(farm.token).allowance(address(this), rate.pool);
if (currentAllowance < amtToTransfer) {
IERC20(farm.token).safeIncreaseAllowance(rate.pool, amtToTransfer.sub(currentAllowance));
}
// Deposit to pool
ILiquidityPool(rate.pool).depositFor(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: amtToTransfer,
refunded: 0
});
} else { // If user wants withdrawn and no private farming
IERC20(farm.token).safeTransfer(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: 0,
refunded: amtToTransfer
});
}
}
emit AssetsFinalized(msg.sender, results);
}
function getRateAdjustedAmounts(uint256 balance, address token) public override view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived) {
RateData memory rateInfo = tokenRates[token];
// Amount eligible to be transferred for Toke
uint256 effectiveTokenBalance =
balance.mul(rateInfo.overNumerator).div(rateInfo.overDenominator);
// Amount to be withdrawn or sent to private farming
uint256 ineffectiveTokenBalance =
balance.mul(rateInfo.overDenominator.sub(rateInfo.overNumerator))
.div(rateInfo.overDenominator);
uint256 actual =
effectiveTokenBalance.mul(rateInfo.tokeDenominator).div(rateInfo.tokeNumerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actual);
}
function getRates() external override view returns (RateData[] memory rates) {
uint256 length = supportedTokenAddresses.length();
rates = new RateData[](length);
for (uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
rates[i] = tokenRates[token];
}
}
function getAccountData(address account) external view override returns (AccountData[] memory data) {
uint256 length = supportedTokenAddresses.length();
data = new AccountData[](length);
for(uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
data[i] = accountData[account][token];
data[i].token = token;
}
}
function getSupportedTokens() external view override returns (SupportedTokenData[] memory supportedTokensArray) {
uint256 supportedTokensLength = supportedTokenAddresses.length();
supportedTokensArray = new SupportedTokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
supportedTokensArray[i] = supportedTokens[supportedTokenAddresses.at(i)];
}
return supportedTokensArray;
}
function _hasEnded() private view returns (bool) {
return durationInfo.startingBlock > 0 && block.number >= durationInfo.blockDuration + durationInfo.startingBlock;
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface ICoreEvent {
struct SupportedTokenData {
address token;
uint256 maxUserLimit;
bool systemFinalized; // Whether or not the system is done setting rates, doing transfers, for this token
}
struct DurationInfo {
uint256 startingBlock;
uint256 blockDuration; // Block duration of the deposit/withdraw stage
}
struct RateData {
address token;
uint256 tokeNumerator;
uint256 tokeDenominator;
uint256 overNumerator;
uint256 overDenominator;
address pool;
}
struct TokenData {
address token;
uint256 amount;
}
struct AccountData {
address token; // Address of the allowed token deposited
uint256 depositedBalance;
bool finalized; // Has the user either taken their refund or sent to farming. Will not be set on swapped but undersubscribed tokens.
}
struct FinalizedAccountData {
address token;
uint256 transferredToFarm;
uint256 refunded;
}
struct TokenFarming {
address token; // address of the allowed token deposited
bool sendToFarming; // Refund is default
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event TreasurySet(address treasury);
event DurationSet(DurationInfo duration);
event DurationIncreased(DurationInfo duration);
event Deposited(address depositor, TokenData[] tokenInfo);
event Withdrawn(address withdrawer, TokenData[] tokenInfo);
event RatesPublished(RateData[] ratesData);
event AssetsFinalized(address user, FinalizedAccountData[] data);
event TreasuryTransfer(TokenData[] tokens);
event WhitelistConfigured(WhitelistSettings settings);
event SetNoSwap(address[] tokens);
//==========================================
// Initial setup operations
//==========================================
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings memory settings) external;
/// @notice defines the length in blocks the round will run for
/// @notice round is started via this call and it is only callable one time
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for
function setDuration(uint256 blockDuration) external;
/// @notice adds tokens to support
/// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) external;
//==========================================
// Stage 1 timeframe operations
//==========================================
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
/// @param proof Merkle proof for the user. Only required if whitelistSettings.enabled
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external;
/// @notice withdraws tokens from the round contract
/// @param tokenData an array of token structs
function withdraw(TokenData[] calldata tokenData) external;
/// @notice extends the deposit/withdraw stage
/// @notice Only extendable if no tokens have been finalized and no rates set
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for. Must be greater than original
function increaseDuration(uint256 blockDuration) external;
//==========================================
// Stage 1 -> 2 transition operations
//==========================================
/// @notice once the expected duration has passed, publish the Toke and over subscription rates
/// @notice tokens which do not have a published rate will have their users forced to withdraw all funds
/// @dev pass a tokeNumerator of 0 to delete a set rate
/// @dev Cannot be called for a token once transferToTreasury/setNoSwap has been called for that token
function setRates(RateData[] calldata rates) external;
/// @notice Allows the owner to transfer the effective balance of a token based on the set rate to the treasury
/// @dev only callable by owner and if rates have been set
/// @dev is only callable one time for a token
function transferToTreasury(address[] calldata tokens) external;
/// @notice Marks a token as finalized but not swapping
/// @dev complement to transferToTreasury which is for tokens that will be swapped, this one for ones that won't
function setNoSwap(address[] calldata tokens) external;
//==========================================
// Stage 2 operations
//==========================================
/// @notice Once rates have been published, and the token finalized via transferToTreasury/setNoSwap, either refunds or sends to private farming
/// @param tokens an array of tokens and whether to send them to private farming. False on farming will send back to user.
function finalize(TokenFarming[] calldata tokens) external;
//==========================================
// View operations
//==========================================
/// @notice Breaks down the balance according to the published rates
/// @dev only callable after rates have been set
function getRateAdjustedAmounts(uint256 balance, address token) external view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived);
/// @notice return the published rates for the tokens
/// @return rates an array of rates for the provided tokens
function getRates() external view returns (RateData[] memory rates);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account) external view returns (AccountData[] calldata data);
/// @notice get all tokens currently supported by the contract
/// @return supportedTokensArray an array of supported token structs
function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Toke is ERC20Pausable, Ownable {
uint256 private constant SUPPLY = 100_000_000e18;
constructor() public ERC20("Tokemak", "TOKE") {
_mint(msg.sender, SUPPLY); // 100M
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// 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.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract TestOracle is Ownable {
//solhint-disable-next-line no-empty-blocks
constructor() public Ownable() { }
uint80 public _roundId = 92233720368547768165;
int256 public _answer = 344698605527;
uint256 public _startedAt = 1631220008;
uint256 public _updatedAt = 1631220008;
uint80 public _answeredInRound = 92233720368547768165;
function setLatestRoundData(uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound) external onlyOwner {
_roundId = roundId;
_answer = answer;
_startedAt = startedAt;
_updatedAt = updatedAt;
_answeredInRound = answeredInRound;
}
function latestRoundData()
public
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return (_roundId, _answer, _startedAt, _updatedAt, _answeredInRound);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract TestnetToken is ERC20Pausable, Ownable {
//solhint-disable-next-line no-empty-blocks
constructor(string memory name, string memory symbol, uint8 decimals) public ERC20(name, symbol) {
_setupDecimals(decimals);
}
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
function burn(address from, uint256 amount) external onlyOwner {
_burn(from, amount);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IStaking.sol";
/// @title Tokemak Redeem Contract
/// @notice Converts PreToke to Toke
/// @dev Can only be used when fromToken has been unpaused
contract Redeem is Ownable {
using SafeERC20 for IERC20;
address public immutable fromToken;
address public immutable toToken;
address public immutable stakingContract;
uint256 public immutable expirationBlock;
uint256 public immutable stakingSchedule;
/// @notice Redeem Constructor
/// @dev approves max uint256 on creation for the toToken against the staking contract
/// @param _fromToken the token users will convert from
/// @param _toToken the token users will convert to
/// @param _stakingContract the staking contract
/// @param _expirationBlock a block number at which the owner can withdraw the full balance of toToken
constructor(
address _fromToken,
address _toToken,
address _stakingContract,
uint256 _expirationBlock,
uint256 _stakingSchedule
) public {
require(_fromToken != address(0), "INVALID_FROMTOKEN");
require(_toToken != address(0), "INVALID_TOTOKEN");
require(_stakingContract != address(0), "INVALID_STAKING");
fromToken = _fromToken;
toToken = _toToken;
stakingContract = _stakingContract;
expirationBlock = _expirationBlock;
stakingSchedule = _stakingSchedule;
//Approve staking contract for toToken to allow for staking within convert()
IERC20(_toToken).safeApprove(_stakingContract, type(uint256).max);
}
/// @notice Allows a holder of fromToken to convert into toToken and simultaneously stake within the stakingContract
/// @dev a user must approve this contract in order for it to burnFrom()
function convert() external {
uint256 fromBal = IERC20(fromToken).balanceOf(msg.sender);
require(fromBal > 0, "INSUFFICIENT_BALANCE");
ERC20Burnable(fromToken).burnFrom(msg.sender, fromBal);
IStaking(stakingContract).depositFor(msg.sender, fromBal, stakingSchedule);
}
/// @notice Allows the claim on the toToken balance after the expiration has passed
/// @dev callable only by owner
function recoupRemaining() external onlyOwner {
require(block.number >= expirationBlock, "EXPIRATION_NOT_PASSED");
uint256 bal = IERC20(toToken).balanceOf(address(this));
IERC20(toToken).safeTransfer(msg.sender, bal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @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 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract Rewards is Ownable {
using SafeMath for uint256;
using ECDSA for bytes32;
using SafeERC20 for IERC20;
mapping(address => uint256) public claimedAmounts;
event SignerSet(address newSigner);
event Claimed(uint256 cycle, address recipient, uint256 amount);
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct Recipient {
uint256 chainId;
uint256 cycle;
address wallet;
uint256 amount;
}
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant RECIPIENT_TYPEHASH =
keccak256("Recipient(uint256 chainId,uint256 cycle,address wallet,uint256 amount)");
bytes32 private immutable domainSeparator;
IERC20 public immutable tokeToken;
address public rewardsSigner;
constructor(IERC20 token, address signerAddress) public {
require(address(token) != address(0), "Invalid TOKE Address");
require(signerAddress != address(0), "Invalid Signer Address");
tokeToken = token;
rewardsSigner = signerAddress;
domainSeparator = _hashDomain(
EIP712Domain({
name: "TOKE Distribution",
version: "1",
chainId: _getChainID(),
verifyingContract: address(this)
})
);
}
function _hashDomain(EIP712Domain memory eip712Domain) private pure returns (bytes32) {
return
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
function _hashRecipient(Recipient memory recipient) private pure returns (bytes32) {
return
keccak256(
abi.encode(
RECIPIENT_TYPEHASH,
recipient.chainId,
recipient.cycle,
recipient.wallet,
recipient.amount
)
);
}
function _hash(Recipient memory recipient) private view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, _hashRecipient(recipient)));
}
function _getChainID() private pure returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function setSigner(address newSigner) external onlyOwner {
require(newSigner != address(0), "Invalid Signer Address");
rewardsSigner = newSigner;
}
function getClaimableAmount(
Recipient calldata recipient
) external view returns (uint256) {
return recipient.amount.sub(claimedAmounts[recipient.wallet]);
}
function claim(
Recipient calldata recipient,
uint8 v,
bytes32 r,
bytes32 s // bytes calldata signature
) external {
address signatureSigner = _hash(recipient).recover(v, r, s);
require(signatureSigner == rewardsSigner, "Invalid Signature");
require(recipient.chainId == _getChainID(), "Invalid chainId");
require(recipient.wallet == msg.sender, "Sender wallet Mismatch");
uint256 claimableAmount = recipient.amount.sub(claimedAmounts[recipient.wallet]);
require(claimableAmount > 0, "Invalid claimable amount");
require(tokeToken.balanceOf(address(this)) >= claimableAmount, "Insufficient Funds");
claimedAmounts[recipient.wallet] = claimedAmounts[recipient.wallet].add(claimableAmount);
tokeToken.safeTransfer(recipient.wallet, claimableAmount);
emit Claimed(recipient.cycle, recipient.wallet, claimableAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
contract UniswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable UNISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable UNISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
require(address(router) != address(0), "INVALID_ROUTER");
require(address(factory) != address(0), "INVALID_FACTORY");
UNISWAP_ROUTER = router;
UNISWAP_FACTORY = factory;
}
/// @notice Deploys liq to Uniswap LP pool
/// @dev Calls to external contract
/// @param data Bytes containing token addrs, amounts, pool addr, dealine to interact with Uni router
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
UNISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
/// @notice Withdraws liq from Uni LP pool
/// @dev Calls to external contract
/// @param data Bytes contains tokens addrs, amounts, liq, pool addr, dealine for Uni router
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = UNISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
UNISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(UNISWAP_ROUTER));
if(currentAllowance > 0) {
token.safeDecreaseAllowance(address(UNISWAP_ROUTER), currentAllowance);
}
token.safeIncreaseAllowance(address(UNISWAP_ROUTER), amount);
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// We import the contract so truffle compiles it, and we have the ABI
// available when working from truffle console.
import "@gnosis.pm/mock-contract/contracts/MockContract.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2ERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol" as ISushiswapV2Router;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol" as ISushiswapV2Factory;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol" as ISushiswapV2ERC20;
import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts/proxy/ProxyAdmin.sol";
pragma solidity ^0.6.0;
interface MockInterface {
/**
* @dev After calling this method, the mock will return `response` when it is called
* with any calldata that is not mocked more specifically below
* (e.g. using givenMethodReturn).
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenAnyReturn(bytes calldata response) external;
function givenAnyReturnBool(bool response) external;
function givenAnyReturnUint(uint response) external;
function givenAnyReturnAddress(address response) external;
function givenAnyRevert() external;
function givenAnyRevertWithMessage(string calldata message) external;
function givenAnyRunOutOfGas() external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called regardless of arguments. If the methodId and arguments
* are mocked more specifically (using `givenMethodAndArguments`) the latter
* will take precedence.
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenMethodReturn(bytes calldata method, bytes calldata response) external;
function givenMethodReturnBool(bytes calldata method, bool response) external;
function givenMethodReturnUint(bytes calldata method, uint response) external;
function givenMethodReturnAddress(bytes calldata method, address response) external;
function givenMethodRevert(bytes calldata method) external;
function givenMethodRevertWithMessage(bytes calldata method, string calldata message) external;
function givenMethodRunOutOfGas(bytes calldata method) external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called with matching arguments. These exact calldataMocks will take
* precedence over all other calldataMocks.
* @param call ABI encoded calldata (methodId and arguments)
* @param response ABI encoded response that will be returned if contract is invoked with calldata
*/
function givenCalldataReturn(bytes calldata call, bytes calldata response) external;
function givenCalldataReturnBool(bytes calldata call, bool response) external;
function givenCalldataReturnUint(bytes calldata call, uint response) external;
function givenCalldataReturnAddress(bytes calldata call, address response) external;
function givenCalldataRevert(bytes calldata call) external;
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) external;
function givenCalldataRunOutOfGas(bytes calldata call) external;
/**
* @dev Returns the number of times anything has been called on this mock since last reset
*/
function invocationCount() external returns (uint);
/**
* @dev Returns the number of times the given method has been called on this mock since last reset
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
*/
function invocationCountForMethod(bytes calldata method) external returns (uint);
/**
* @dev Returns the number of times this mock has been called with the exact calldata since last reset.
* @param call ABI encoded calldata (methodId and arguments)
*/
function invocationCountForCalldata(bytes calldata call) external returns (uint);
/**
* @dev Resets all mocked methods and invocation counts.
*/
function reset() external;
}
/**
* Implementation of the MockInterface.
*/
contract MockContract is MockInterface {
enum MockType { Return, Revert, OutOfGas }
bytes32 public constant MOCKS_LIST_START = hex"01";
bytes public constant MOCKS_LIST_END = "0xff";
bytes32 public constant MOCKS_LIST_END_HASH = keccak256(MOCKS_LIST_END);
bytes4 public constant SENTINEL_ANY_MOCKS = hex"01";
bytes public constant DEFAULT_FALLBACK_VALUE = abi.encode(false);
// A linked list allows easy iteration and inclusion checks
mapping(bytes32 => bytes) calldataMocks;
mapping(bytes => MockType) calldataMockTypes;
mapping(bytes => bytes) calldataExpectations;
mapping(bytes => string) calldataRevertMessage;
mapping(bytes32 => uint) calldataInvocations;
mapping(bytes4 => bytes4) methodIdMocks;
mapping(bytes4 => MockType) methodIdMockTypes;
mapping(bytes4 => bytes) methodIdExpectations;
mapping(bytes4 => string) methodIdRevertMessages;
mapping(bytes32 => uint) methodIdInvocations;
MockType fallbackMockType;
bytes fallbackExpectation = DEFAULT_FALLBACK_VALUE;
string fallbackRevertMessage;
uint invocations;
uint resetCount;
constructor() public {
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
}
function trackCalldataMock(bytes memory call) private {
bytes32 callHash = keccak256(call);
if (calldataMocks[callHash].length == 0) {
calldataMocks[callHash] = calldataMocks[MOCKS_LIST_START];
calldataMocks[MOCKS_LIST_START] = call;
}
}
function trackMethodIdMock(bytes4 methodId) private {
if (methodIdMocks[methodId] == 0x0) {
methodIdMocks[methodId] = methodIdMocks[SENTINEL_ANY_MOCKS];
methodIdMocks[SENTINEL_ANY_MOCKS] = methodId;
}
}
function _givenAnyReturn(bytes memory response) internal {
fallbackMockType = MockType.Return;
fallbackExpectation = response;
}
function givenAnyReturn(bytes calldata response) override external {
_givenAnyReturn(response);
}
function givenAnyReturnBool(bool response) override external {
uint flag = response ? 1 : 0;
_givenAnyReturn(uintToBytes(flag));
}
function givenAnyReturnUint(uint response) override external {
_givenAnyReturn(uintToBytes(response));
}
function givenAnyReturnAddress(address response) override external {
_givenAnyReturn(uintToBytes(uint(response)));
}
function givenAnyRevert() override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = "";
}
function givenAnyRevertWithMessage(string calldata message) override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = message;
}
function givenAnyRunOutOfGas() override external {
fallbackMockType = MockType.OutOfGas;
}
function _givenCalldataReturn(bytes memory call, bytes memory response) private {
calldataMockTypes[call] = MockType.Return;
calldataExpectations[call] = response;
trackCalldataMock(call);
}
function givenCalldataReturn(bytes calldata call, bytes calldata response) override external {
_givenCalldataReturn(call, response);
}
function givenCalldataReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenCalldataReturn(call, uintToBytes(flag));
}
function givenCalldataReturnUint(bytes calldata call, uint response) override external {
_givenCalldataReturn(call, uintToBytes(response));
}
function givenCalldataReturnAddress(bytes calldata call, address response) override external {
_givenCalldataReturn(call, uintToBytes(uint(response)));
}
function _givenMethodReturn(bytes memory call, bytes memory response) private {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Return;
methodIdExpectations[method] = response;
trackMethodIdMock(method);
}
function givenMethodReturn(bytes calldata call, bytes calldata response) override external {
_givenMethodReturn(call, response);
}
function givenMethodReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenMethodReturn(call, uintToBytes(flag));
}
function givenMethodReturnUint(bytes calldata call, uint response) override external {
_givenMethodReturn(call, uintToBytes(response));
}
function givenMethodReturnAddress(bytes calldata call, address response) override external {
_givenMethodReturn(call, uintToBytes(uint(response)));
}
function givenCalldataRevert(bytes calldata call) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = "";
trackCalldataMock(call);
}
function givenMethodRevert(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
trackMethodIdMock(method);
}
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = message;
trackCalldataMock(call);
}
function givenMethodRevertWithMessage(bytes calldata call, string calldata message) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
methodIdRevertMessages[method] = message;
trackMethodIdMock(method);
}
function givenCalldataRunOutOfGas(bytes calldata call) override external {
calldataMockTypes[call] = MockType.OutOfGas;
trackCalldataMock(call);
}
function givenMethodRunOutOfGas(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.OutOfGas;
trackMethodIdMock(method);
}
function invocationCount() override external returns (uint) {
return invocations;
}
function invocationCountForMethod(bytes calldata call) override external returns (uint) {
bytes4 method = bytesToBytes4(call);
return methodIdInvocations[keccak256(abi.encodePacked(resetCount, method))];
}
function invocationCountForCalldata(bytes calldata call) override external returns (uint) {
return calldataInvocations[keccak256(abi.encodePacked(resetCount, call))];
}
function reset() override external {
// Reset all exact calldataMocks
bytes memory nextMock = calldataMocks[MOCKS_LIST_START];
bytes32 mockHash = keccak256(nextMock);
// We cannot compary bytes
while(mockHash != MOCKS_LIST_END_HASH) {
// Reset all mock maps
calldataMockTypes[nextMock] = MockType.Return;
calldataExpectations[nextMock] = hex"";
calldataRevertMessage[nextMock] = "";
// Set next mock to remove
nextMock = calldataMocks[mockHash];
// Remove from linked list
calldataMocks[mockHash] = "";
// Update mock hash
mockHash = keccak256(nextMock);
}
// Clear list
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
// Reset all any calldataMocks
bytes4 nextAnyMock = methodIdMocks[SENTINEL_ANY_MOCKS];
while(nextAnyMock != SENTINEL_ANY_MOCKS) {
bytes4 currentAnyMock = nextAnyMock;
methodIdMockTypes[currentAnyMock] = MockType.Return;
methodIdExpectations[currentAnyMock] = hex"";
methodIdRevertMessages[currentAnyMock] = "";
nextAnyMock = methodIdMocks[currentAnyMock];
// Remove from linked list
methodIdMocks[currentAnyMock] = 0x0;
}
// Clear list
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
fallbackExpectation = DEFAULT_FALLBACK_VALUE;
fallbackMockType = MockType.Return;
invocations = 0;
resetCount += 1;
}
function useAllGas() private {
while(true) {
bool s;
assembly {
//expensive call to EC multiply contract
s := call(sub(gas(), 2000), 6, 0, 0x0, 0xc0, 0x0, 0x60)
}
}
}
function bytesToBytes4(bytes memory b) private pure returns (bytes4) {
bytes4 out;
for (uint i = 0; i < 4; i++) {
out |= bytes4(b[i] & 0xFF) >> (i * 8);
}
return out;
}
function uintToBytes(uint256 x) private pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
function updateInvocationCount(bytes4 methodId, bytes memory originalMsgData) public {
require(msg.sender == address(this), "Can only be called from the contract itself");
invocations += 1;
methodIdInvocations[keccak256(abi.encodePacked(resetCount, methodId))] += 1;
calldataInvocations[keccak256(abi.encodePacked(resetCount, originalMsgData))] += 1;
}
fallback () payable external {
bytes4 methodId;
assembly {
methodId := calldataload(0)
}
// First, check exact matching overrides
if (calldataMockTypes[msg.data] == MockType.Revert) {
revert(calldataRevertMessage[msg.data]);
}
if (calldataMockTypes[msg.data] == MockType.OutOfGas) {
useAllGas();
}
bytes memory result = calldataExpectations[msg.data];
// Then check method Id overrides
if (result.length == 0) {
if (methodIdMockTypes[methodId] == MockType.Revert) {
revert(methodIdRevertMessages[methodId]);
}
if (methodIdMockTypes[methodId] == MockType.OutOfGas) {
useAllGas();
}
result = methodIdExpectations[methodId];
}
// Last, use the fallback override
if (result.length == 0) {
if (fallbackMockType == MockType.Revert) {
revert(fallbackRevertMessage);
}
if (fallbackMockType == MockType.OutOfGas) {
useAllGas();
}
result = fallbackExpectation;
}
// Record invocation as separate call so we don't rollback in case we are called with STATICCALL
(, bytes memory r) = address(this).call{gas: 100000}(abi.encodeWithSignature("updateInvocationCount(bytes4,bytes)", methodId, msg.data));
assert(r.length == 0);
assembly {
return(add(0x20, result), mload(result))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/AccessControl.sol";
import "../utils/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @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 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin {
_upgradeTo(newImplementation);
Address.functionDelegateCall(newImplementation, data);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/Ownable.sol";
import "./TransparentUpgradeableProxy.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// 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.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/balancer/IBalancerPool.sol";
contract BalancerController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
/// @notice Used to deploy liquidity to a Balancer pool
/// @dev Calls into external contract
/// @param poolAddress Address of pool to have liquidity added
/// @param tokens Array of ERC20 tokens to be added to pool
/// @param amounts Corresponding array of amounts of tokens to be added to a pool
/// @param data Bytes data passed from manager containing information to be passed to the balancer pool
function deploy(
address poolAddress,
IERC20[] calldata tokens,
uint256[] calldata amounts,
bytes calldata data
) external {
require(tokens.length == amounts.length, "TOKEN_AMOUNTS_COUNT_MISMATCH");
require(tokens.length > 0, "TOKENS_AMOUNTS_NOT_PROVIDED");
for (uint256 i = 0; i < tokens.length; i++) {
_approve(tokens[i], poolAddress, amounts[i]);
}
//Notes:
// - If your pool is eligible for weekly BAL rewards, they will be distributed to your LPs automatically
// - If you contribute significant long-term liquidity to the platform, you can apply to have smart contract deployment gas costs reimbursed from the Balancer Ecosystem fund
// - The pool is the LP token, All pools in Balancer are also ERC20 tokens known as BPTs \(Balancer Pool Tokens\)
(uint256 poolAmountOut, uint256[] memory maxAmountsIn) =
abi.decode(data, (uint256, uint256[]));
IBalancerPool(poolAddress).joinPool(poolAmountOut, maxAmountsIn);
}
/// @notice Used to withdraw liquidity from balancer pools
/// @dev Calls into external contract
/// @param poolAddress Address of pool to have liquidity withdrawn
/// @param data Data to be decoded and passed to pool
function withdraw(address poolAddress, bytes calldata data) external {
(uint256 poolAmountIn, uint256[] memory minAmountsOut) =
abi.decode(data, (uint256, uint256[]));
_approve(IERC20(poolAddress), poolAddress, poolAmountIn);
IBalancerPool(poolAddress).exitPool(poolAmountIn, minAmountsOut);
}
function _approve(IERC20 token, address poolAddress, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), poolAddress);
if(currentAllowance > 0) {
token.safeDecreaseAllowance(poolAddress, currentAllowance);
}
token.safeIncreaseAllowance(poolAddress, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IBalancerPool {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function getBalance(address token) external view returns (uint);
function decimals() external view returns(uint8);
function isFinalized() external view returns (bool);
function getFinalTokens()
external view
returns (address[] memory tokens);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
// solhint-disable-next-line
contract PreToke is ERC20PresetMinterPauser("PreToke", "PTOKE") {
}
| Approve the zeroExRouter's allowance to max if the allowance ever drops below the balance of the token held | function _approve(IERC20 token) internal {
uint256 allowance = token.allowance(address(this), address(zeroExRouter));
if (allowance < token.balanceOf(address(this))) {
uint256 amount = token.balanceOf(address(this)).sub(allowance);
token.safeIncreaseAllowance(address(zeroExRouter), amount);
}
}
| 10,126,055 |
./full_match/137/0xe558726C468Ccc21cc09ca4B8B46131dC1002923/sources/project_/contracts/Exchange.sol | Sends tokens mistakenly sent directly to the `Exchange` to the fee wallet (the `receive` function rejects ETH except when wrapping/unwrapping)/ | function skim(address tokenAddress) external onlyAdmin {
AssetRegistry.skim(tokenAddress, _feeWallet);
}
| 4,762,008 |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity =0.6.10;
pragma experimental ABIEncoderV2;
// File: contracts/packages/oz/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/packages/oz/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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 virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/packages/oz/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/interfaces/OtokenInterface.sol
interface OtokenInterface {
function addressBook() external view returns (address);
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
function init(
address _addressBook,
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external;
function getOtokenDetails()
external
view
returns (
address,
address,
address,
uint256,
uint256,
bool
);
function mintOtoken(address account, uint256 amount) external;
function burnOtoken(address account, uint256 amount) external;
}
// File: contracts/interfaces/OracleInterface.sol
interface OracleInterface {
function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool);
function getDisputer() external view returns (address);
function getPricer(address _asset) external view returns (address);
function getPrice(address _asset) external view returns (uint256);
function getPricerLockingPeriod(address _pricer) external view returns (uint256);
function getPricerDisputePeriod(address _pricer) external view returns (uint256);
function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256);
// Non-view function
function setAssetPricer(address _asset, address _pricer) external;
function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;
function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function disputeExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function setDisputer(address _disputer) external;
}
// File: contracts/interfaces/ERC20Interface.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface ERC20Interface {
/**
* @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);
function decimals() external view returns (uint8);
/**
* @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/packages/oz/SignedSafeMath.sol
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 private constant _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File: contracts/libs/SignedConverter.sol
/**
* @title SignedConverter
* @author Opyn Team
* @notice A library to convert an unsigned integer to signed integer or signed integer to unsigned integer.
*/
library SignedConverter {
/**
* @notice convert an unsigned integer to a signed integer
* @param a uint to convert into a signed integer
* @return converted signed integer
*/
function uintToInt(uint256 a) internal pure returns (int256) {
require(a < 2**255, "FixedPointInt256: out of int range");
return int256(a);
}
/**
* @notice convert a signed integer to an unsigned integer
* @param a int to convert into an unsigned integer
* @return converted unsigned integer
*/
function intToUint(int256 a) internal pure returns (uint256) {
if (a < 0) {
return uint256(-a);
} else {
return uint256(a);
}
}
}
// File: contracts/libs/FixedPointInt256.sol
/**
* @title FixedPointInt256
* @author Opyn Team
* @notice FixedPoint library
*/
library FPI {
using SignedSafeMath for int256;
using SignedConverter for int256;
using SafeMath for uint256;
using SignedConverter for uint256;
int256 private constant SCALING_FACTOR = 1e27;
uint256 private constant BASE_DECIMALS = 27;
struct FixedPointInt {
int256 value;
}
/**
* @notice constructs an `FixedPointInt` from an unscaled int, e.g., `b=5` gets stored internally as `5**27`.
* @param a int to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledInt(int256 a) internal pure returns (FixedPointInt memory) {
return FixedPointInt(a.mul(SCALING_FACTOR));
}
/**
* @notice constructs an FixedPointInt from an scaled uint with {_decimals} decimals
* Examples:
* (1) USDC decimals = 6
* Input: 5 * 1e6 USDC => Output: 5 * 1e27 (FixedPoint 5.0 USDC)
* (2) cUSDC decimals = 8
* Input: 5 * 1e6 cUSDC => Output: 5 * 1e25 (FixedPoint 0.05 cUSDC)
* @param _a uint256 to convert into a FixedPoint.
* @param _decimals original decimals _a has
* @return the converted FixedPoint, with 27 decimals.
*/
function fromScaledUint(uint256 _a, uint256 _decimals) internal pure returns (FixedPointInt memory) {
FixedPointInt memory fixedPoint;
if (_decimals == BASE_DECIMALS) {
fixedPoint = FixedPointInt(_a.uintToInt());
} else if (_decimals > BASE_DECIMALS) {
uint256 exp = _decimals.sub(BASE_DECIMALS);
fixedPoint = FixedPointInt((_a.div(10**exp)).uintToInt());
} else {
uint256 exp = BASE_DECIMALS - _decimals;
fixedPoint = FixedPointInt((_a.mul(10**exp)).uintToInt());
}
return fixedPoint;
}
/**
* @notice convert a FixedPointInt number to an uint256 with a specific number of decimals
* @param _a FixedPointInt to convert
* @param _decimals number of decimals that the uint256 should be scaled to
* @param _roundDown True to round down the result, False to round up
* @return the converted uint256
*/
function toScaledUint(
FixedPointInt memory _a,
uint256 _decimals,
bool _roundDown
) internal pure returns (uint256) {
uint256 scaledUint;
if (_decimals == BASE_DECIMALS) {
scaledUint = _a.value.intToUint();
} else if (_decimals > BASE_DECIMALS) {
uint256 exp = _decimals - BASE_DECIMALS;
scaledUint = (_a.value).intToUint().mul(10**exp);
} else {
uint256 exp = BASE_DECIMALS - _decimals;
uint256 tailing;
if (!_roundDown) {
uint256 remainer = (_a.value).intToUint().mod(10**exp);
if (remainer > 0) tailing = 1;
}
scaledUint = (_a.value).intToUint().div(10**exp).add(tailing);
}
return scaledUint;
}
/**
* @notice add two signed integers, a + b
* @param a FixedPointInt
* @param b FixedPointInt
* @return sum of the two signed integers
*/
function add(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) {
return FixedPointInt(a.value.add(b.value));
}
/**
* @notice subtract two signed integers, a-b
* @param a FixedPointInt
* @param b FixedPointInt
* @return difference of two signed integers
*/
function sub(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) {
return FixedPointInt(a.value.sub(b.value));
}
/**
* @notice multiply two signed integers, a by b
* @param a FixedPointInt
* @param b FixedPointInt
* @return mul of two signed integers
*/
function mul(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) {
return FixedPointInt((a.value.mul(b.value)) / SCALING_FACTOR);
}
/**
* @notice divide two signed integers, a by b
* @param a FixedPointInt
* @param b FixedPointInt
* @return div of two signed integers
*/
function div(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) {
return FixedPointInt((a.value.mul(SCALING_FACTOR)) / b.value);
}
/**
* @notice minimum between two signed integers, a and b
* @param a FixedPointInt
* @param b FixedPointInt
* @return min of two signed integers
*/
function min(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) {
return a.value < b.value ? a : b;
}
/**
* @notice maximum between two signed integers, a and b
* @param a FixedPointInt
* @param b FixedPointInt
* @return max of two signed integers
*/
function max(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) {
return a.value > b.value ? a : b;
}
/**
* @notice is a is equal to b
* @param a FixedPointInt
* @param b FixedPointInt
* @return True if equal, False if not
*/
function isEqual(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) {
return a.value == b.value;
}
/**
* @notice is a greater than b
* @param a FixedPointInt
* @param b FixedPointInt
* @return True if a > b, False if not
*/
function isGreaterThan(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) {
return a.value > b.value;
}
/**
* @notice is a greater than or equal to b
* @param a FixedPointInt
* @param b FixedPointInt
* @return True if a >= b, False if not
*/
function isGreaterThanOrEqual(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) {
return a.value >= b.value;
}
/**
* @notice is a is less than b
* @param a FixedPointInt
* @param b FixedPointInt
* @return True if a < b, False if not
*/
function isLessThan(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) {
return a.value < b.value;
}
/**
* @notice is a less than or equal to b
* @param a FixedPointInt
* @param b FixedPointInt
* @return True if a <= b, False if not
*/
function isLessThanOrEqual(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) {
return a.value <= b.value;
}
}
// File: contracts/libs/MarginVault.sol
/**
* MarginVault Error Codes
* V1: invalid short otoken amount
* V2: invalid short otoken index
* V3: short otoken address mismatch
* V4: invalid long otoken amount
* V5: invalid long otoken index
* V6: long otoken address mismatch
* V7: invalid collateral amount
* V8: invalid collateral token index
* V9: collateral token address mismatch
*/
/**
* @title MarginVault
* @author Opyn Team
* @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults.
* Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have.
*/
library MarginVault {
using SafeMath for uint256;
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
/**
* @dev increase the short oToken balance in a vault when a new oToken is minted
* @param _vault vault to add or increase the short position in
* @param _shortOtoken address of the _shortOtoken being minted from the user's vault
* @param _amount number of _shortOtoken being minted from the user's vault
* @param _index index of _shortOtoken in the user's vault.shortOtokens array
*/
function addShort(
Vault storage _vault,
address _shortOtoken,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V1");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) {
_vault.shortOtokens.push(_shortOtoken);
_vault.shortAmounts.push(_amount);
} else {
require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2");
address existingShort = _vault.shortOtokens[_index];
require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3");
_vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount);
_vault.shortOtokens[_index] = _shortOtoken;
}
}
/**
* @dev decrease the short oToken balance in a vault when an oToken is burned
* @param _vault vault to decrease short position in
* @param _shortOtoken address of the _shortOtoken being reduced in the user's vault
* @param _amount number of _shortOtoken being reduced in the user's vault
* @param _index index of _shortOtoken in the user's vault.shortOtokens array
*/
function removeShort(
Vault storage _vault,
address _shortOtoken,
uint256 _amount,
uint256 _index
) external {
// check that the removed short oToken exists in the vault at the specified index
require(_index < _vault.shortOtokens.length, "V2");
require(_vault.shortOtokens[_index] == _shortOtoken, "V3");
uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount);
if (newShortAmount == 0) {
delete _vault.shortOtokens[_index];
}
_vault.shortAmounts[_index] = newShortAmount;
}
/**
* @dev increase the long oToken balance in a vault when an oToken is deposited
* @param _vault vault to add a long position to
* @param _longOtoken address of the _longOtoken being added to the user's vault
* @param _amount number of _longOtoken the protocol is adding to the user's vault
* @param _index index of _longOtoken in the user's vault.longOtokens array
*/
function addLong(
Vault storage _vault,
address _longOtoken,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V4");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) {
_vault.longOtokens.push(_longOtoken);
_vault.longAmounts.push(_amount);
} else {
require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5");
address existingLong = _vault.longOtokens[_index];
require((existingLong == _longOtoken) || (existingLong == address(0)), "V6");
_vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount);
_vault.longOtokens[_index] = _longOtoken;
}
}
/**
* @dev decrease the long oToken balance in a vault when an oToken is withdrawn
* @param _vault vault to remove a long position from
* @param _longOtoken address of the _longOtoken being removed from the user's vault
* @param _amount number of _longOtoken the protocol is removing from the user's vault
* @param _index index of _longOtoken in the user's vault.longOtokens array
*/
function removeLong(
Vault storage _vault,
address _longOtoken,
uint256 _amount,
uint256 _index
) external {
// check that the removed long oToken exists in the vault at the specified index
require(_index < _vault.longOtokens.length, "V5");
require(_vault.longOtokens[_index] == _longOtoken, "V6");
uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount);
if (newLongAmount == 0) {
delete _vault.longOtokens[_index];
}
_vault.longAmounts[_index] = newLongAmount;
}
/**
* @dev increase the collateral balance in a vault
* @param _vault vault to add collateral to
* @param _collateralAsset address of the _collateralAsset being added to the user's vault
* @param _amount number of _collateralAsset being added to the user's vault
* @param _index index of _collateralAsset in the user's vault.collateralAssets array
*/
function addCollateral(
Vault storage _vault,
address _collateralAsset,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V7");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) {
_vault.collateralAssets.push(_collateralAsset);
_vault.collateralAmounts.push(_amount);
} else {
require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8");
address existingCollateral = _vault.collateralAssets[_index];
require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9");
_vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount);
_vault.collateralAssets[_index] = _collateralAsset;
}
}
/**
* @dev decrease the collateral balance in a vault
* @param _vault vault to remove collateral from
* @param _collateralAsset address of the _collateralAsset being removed from the user's vault
* @param _amount number of _collateralAsset being removed from the user's vault
* @param _index index of _collateralAsset in the user's vault.collateralAssets array
*/
function removeCollateral(
Vault storage _vault,
address _collateralAsset,
uint256 _amount,
uint256 _index
) external {
// check that the removed collateral exists in the vault at the specified index
require(_index < _vault.collateralAssets.length, "V8");
require(_vault.collateralAssets[_index] == _collateralAsset, "V9");
uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount);
if (newCollateralAmount == 0) {
delete _vault.collateralAssets[_index];
}
_vault.collateralAmounts[_index] = newCollateralAmount;
}
}
// File: contracts/core/MarginCalculator.sol
/**
* @title MarginCalculator
* @author Opyn
* @notice Calculator module that checks if a given vault is valid, calculates margin requirements, and settlement proceeds
*/
contract MarginCalculator is Ownable {
using SafeMath for uint256;
using FPI for FPI.FixedPointInt;
/// @dev decimals option upper bound value, spot shock and oracle deviation
uint256 internal constant SCALING_FACTOR = 27;
/// @dev decimals used by strike price and oracle price
uint256 internal constant BASE = 8;
/// @notice auction length
uint256 public constant AUCTION_TIME = 5400;
/// @dev struct to store all needed vault details
struct VaultDetails {
address shortUnderlyingAsset;
address shortStrikeAsset;
address shortCollateralAsset;
address longUnderlyingAsset;
address longStrikeAsset;
address longCollateralAsset;
uint256 shortStrikePrice;
uint256 shortExpiryTimestamp;
uint256 shortCollateralDecimals;
uint256 longStrikePrice;
uint256 longExpiryTimestamp;
uint256 longCollateralDecimals;
uint256 collateralDecimals;
uint256 vaultType;
bool isShortPut;
bool isLongPut;
bool hasLong;
bool hasShort;
bool hasCollateral;
}
/// @dev oracle deviation value (1e27)
uint256 internal oracleDeviation;
/// @dev FixedPoint 0
FPI.FixedPointInt internal ZERO = FPI.fromScaledUint(0, BASE);
/// @dev mapping to store dust amount per option collateral asset (scaled by collateral asset decimals)
mapping(address => uint256) internal dust;
/// @dev mapping to store array of time to expiry for a given product
mapping(bytes32 => uint256[]) internal timesToExpiryForProduct;
/// @dev mapping to store option upper bound value at specific time to expiry for a given product (1e27)
mapping(bytes32 => mapping(uint256 => uint256)) internal maxPriceAtTimeToExpiry;
/// @dev mapping to store shock value for spot price of a given product (1e27)
mapping(bytes32 => uint256) internal spotShock;
/// @dev oracle module
OracleInterface public oracle;
/// @notice emits an event when collateral dust is updated
event CollateralDustUpdated(address indexed collateral, uint256 dust);
/// @notice emits an event when new time to expiry is added for a specific product
event TimeToExpiryAdded(bytes32 indexed productHash, uint256 timeToExpiry);
/// @notice emits an event when new upper bound value is added for a specific time to expiry timestamp
event MaxPriceAdded(bytes32 indexed productHash, uint256 timeToExpiry, uint256 value);
/// @notice emits an event when updating upper bound value at specific expiry timestamp
event MaxPriceUpdated(bytes32 indexed productHash, uint256 timeToExpiry, uint256 oldValue, uint256 newValue);
/// @notice emits an event when spot shock value is updated for a specific product
event SpotShockUpdated(bytes32 indexed product, uint256 spotShock);
/// @notice emits an event when oracle deviation value is updated
event OracleDeviationUpdated(uint256 oracleDeviation);
/**
* @notice constructor
* @param _oracle oracle module address
*/
constructor(address _oracle) public {
require(_oracle != address(0), "MarginCalculator: invalid oracle address");
oracle = OracleInterface(_oracle);
}
/**
* @notice set dust amount for collateral asset
* @dev can only be called by owner
* @param _collateral collateral asset address
* @param _dust dust amount, should be scaled by collateral asset decimals
*/
function setCollateralDust(address _collateral, uint256 _dust) external onlyOwner {
require(_dust > 0, "MarginCalculator: dust amount should be greater than zero");
dust[_collateral] = _dust;
emit CollateralDustUpdated(_collateral, _dust);
}
/**
* @notice set product upper bound values
* @dev can only be called by owner
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _collateral otoken collateral asset
* @param _isPut otoken type
* @param _timesToExpiry array of times to expiry timestamp
* @param _values upper bound values array
*/
function setUpperBoundValues(
address _underlying,
address _strike,
address _collateral,
bool _isPut,
uint256[] calldata _timesToExpiry,
uint256[] calldata _values
) external onlyOwner {
require(_timesToExpiry.length > 0, "MarginCalculator: invalid times to expiry array");
require(_timesToExpiry.length == _values.length, "MarginCalculator: invalid values array");
// get product hash
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
uint256[] storage expiryArray = timesToExpiryForProduct[productHash];
// check that this is the first expiry to set
// if not, the last expiry should be less than the new one to insert (to make sure the array stay in order)
require(
(expiryArray.length == 0) || (_timesToExpiry[0] > expiryArray[expiryArray.length.sub(1)]),
"MarginCalculator: expiry array is not in order"
);
for (uint256 i = 0; i < _timesToExpiry.length; i++) {
// check that new times array is in order
if (i.add(1) < _timesToExpiry.length) {
require(_timesToExpiry[i] < _timesToExpiry[i.add(1)], "MarginCalculator: time should be in order");
}
require(_values[i] > 0, "MarginCalculator: no expiry upper bound value found");
// add new upper bound value for this product at specific time to expiry
maxPriceAtTimeToExpiry[productHash][_timesToExpiry[i]] = _values[i];
// add new time to expiry to array
expiryArray.push(_timesToExpiry[i]);
emit TimeToExpiryAdded(productHash, _timesToExpiry[i]);
emit MaxPriceAdded(productHash, _timesToExpiry[i], _values[i]);
}
}
/**
* @notice set option upper bound value for specific time to expiry (1e27)
* @dev can only be called by owner
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _collateral otoken collateral asset
* @param _isPut otoken type
* @param _timeToExpiry option time to expiry timestamp
* @param _value upper bound value
*/
function updateUpperBoundValue(
address _underlying,
address _strike,
address _collateral,
bool _isPut,
uint256 _timeToExpiry,
uint256 _value
) external onlyOwner {
require(_value > 0, "MarginCalculator: invalid option upper bound value");
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
uint256 oldMaxPrice = maxPriceAtTimeToExpiry[productHash][_timeToExpiry];
require(oldMaxPrice != 0, "MarginCalculator: upper bound value not found");
// update upper bound value for the time to expiry
maxPriceAtTimeToExpiry[productHash][_timeToExpiry] = _value;
emit MaxPriceUpdated(productHash, _timeToExpiry, oldMaxPrice, _value);
}
/**
* @notice set spot shock value, scaled to 1e27
* @dev can only be called by owner
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _collateral otoken collateral asset
* @param _isPut otoken type
* @param _shockValue spot shock value
*/
function setSpotShock(
address _underlying,
address _strike,
address _collateral,
bool _isPut,
uint256 _shockValue
) external onlyOwner {
require(_shockValue > 0, "MarginCalculator: invalid spot shock value");
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
spotShock[productHash] = _shockValue;
emit SpotShockUpdated(productHash, _shockValue);
}
/**
* @notice set oracle deviation (1e27)
* @dev can only be called by owner
* @param _deviation deviation value
*/
function setOracleDeviation(uint256 _deviation) external onlyOwner {
oracleDeviation = _deviation;
emit OracleDeviationUpdated(_deviation);
}
/**
* @notice get dust amount for collateral asset
* @param _collateral collateral asset address
* @return dust amount
*/
function getCollateralDust(address _collateral) external view returns (uint256) {
return dust[_collateral];
}
/**
* @notice get times to expiry for a specific product
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _collateral otoken collateral asset
* @param _isPut otoken type
* @return array of times to expiry
*/
function getTimesToExpiry(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external view returns (uint256[] memory) {
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
return timesToExpiryForProduct[productHash];
}
/**
* @notice get option upper bound value for specific time to expiry
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _collateral otoken collateral asset
* @param _isPut otoken type
* @param _timeToExpiry option time to expiry timestamp
* @return option upper bound value (1e27)
*/
function getMaxPrice(
address _underlying,
address _strike,
address _collateral,
bool _isPut,
uint256 _timeToExpiry
) external view returns (uint256) {
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
return maxPriceAtTimeToExpiry[productHash][_timeToExpiry];
}
/**
* @notice get spot shock value
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _collateral otoken collateral asset
* @param _isPut otoken type
* @return _shockValue spot shock value (1e27)
*/
function getSpotShock(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external view returns (uint256) {
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
return spotShock[productHash];
}
/**
* @notice get oracle deviation
* @return oracle deviation value (1e27)
*/
function getOracleDeviation() external view returns (uint256) {
return oracleDeviation;
}
/**
* @notice return the collateral required for naked margin vault, in collateral asset decimals
* @dev _shortAmount, _strikePrice and _underlyingPrice should be scaled by 1e8
* @param _underlying underlying asset address
* @param _strike strike asset address
* @param _collateral collateral asset address
* @param _shortAmount amount of short otoken
* @param _strikePrice otoken strike price
* @param _underlyingPrice otoken underlying price
* @param _shortExpiryTimestamp otoken expiry timestamp
* @param _collateralDecimals otoken collateral asset decimals
* @param _isPut otoken type
* @return collateral required for a naked margin vault, in collateral asset decimals
*/
function getNakedMarginRequired(
address _underlying,
address _strike,
address _collateral,
uint256 _shortAmount,
uint256 _strikePrice,
uint256 _underlyingPrice,
uint256 _shortExpiryTimestamp,
uint256 _collateralDecimals,
bool _isPut
) external view returns (uint256) {
bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut);
// scale short amount from 1e8 to 1e27 (oToken is always in 1e8)
FPI.FixedPointInt memory shortAmount = FPI.fromScaledUint(_shortAmount, BASE);
// scale short strike from 1e8 to 1e27
FPI.FixedPointInt memory shortStrike = FPI.fromScaledUint(_strikePrice, BASE);
// scale short underlying price from 1e8 to 1e27
FPI.FixedPointInt memory shortUnderlyingPrice = FPI.fromScaledUint(_underlyingPrice, BASE);
// return required margin, scaled by collateral asset decimals, explicitly rounded up
return
FPI.toScaledUint(
_getNakedMarginRequired(
productHash,
shortAmount,
shortUnderlyingPrice,
shortStrike,
_shortExpiryTimestamp,
_isPut
),
_collateralDecimals,
false
);
}
/**
* @notice return the cash value of an expired oToken, denominated in collateral
* @param _otoken oToken address
* @return how much collateral can be taken out by 1 otoken unit, scaled by 1e8,
* or how much collateral can be taken out for 1 (1e8) oToken
*/
function getExpiredPayoutRate(address _otoken) external view returns (uint256) {
require(_otoken != address(0), "MarginCalculator: Invalid token address");
(
address collateral,
address underlying,
address strikeAsset,
uint256 strikePrice,
uint256 expiry,
bool isPut
) = _getOtokenDetails(_otoken);
require(now >= expiry, "MarginCalculator: Otoken not expired yet");
FPI.FixedPointInt memory cashValueInStrike = _getExpiredCashValue(
underlying,
strikeAsset,
expiry,
strikePrice,
isPut
);
FPI.FixedPointInt memory cashValueInCollateral = _convertAmountOnExpiryPrice(
cashValueInStrike,
strikeAsset,
collateral,
expiry
);
// the exchangeRate was scaled by 1e8, if 1e8 otoken can take out 1 USDC, the exchangeRate is currently 1e8
// we want to return: how much USDC units can be taken out by 1 (1e8 units) oToken
uint256 collateralDecimals = uint256(ERC20Interface(collateral).decimals());
return cashValueInCollateral.toScaledUint(collateralDecimals, true);
}
// structs to avoid stack too deep error
// struct to store shortAmount, shortStrike and shortUnderlyingPrice scaled to 1e27
struct ShortScaledDetails {
FPI.FixedPointInt shortAmount;
FPI.FixedPointInt shortStrike;
FPI.FixedPointInt shortUnderlyingPrice;
}
/**
* @notice check if a specific vault is undercollateralized at a specific chainlink round
* @dev if the vault is of type 0, the function will revert
* @param _vault vault struct
* @param _vaultType vault type (0 for max loss/spread and 1 for naked margin vault)
* @param _vaultLatestUpdate vault latest update (timestamp when latest vault state change happened)
* @param _roundId chainlink round id
* @return isLiquidatable, true if vault is undercollateralized, liquidation price and collateral dust amount
*/
function isLiquidatable(
MarginVault.Vault memory _vault,
uint256 _vaultType,
uint256 _vaultLatestUpdate,
uint256 _roundId
)
external
view
returns (
bool,
uint256,
uint256
)
{
// liquidation is only supported for naked margin vault
require(_vaultType == 1, "MarginCalculator: invalid vault type to liquidate");
VaultDetails memory vaultDetails = _getVaultDetails(_vault, _vaultType);
// can not liquidate vault that have no short position
if (!vaultDetails.hasShort) return (false, 0, 0);
require(now < vaultDetails.shortExpiryTimestamp, "MarginCalculator: can not liquidate expired position");
(uint256 price, uint256 timestamp) = oracle.getChainlinkRoundData(
vaultDetails.shortUnderlyingAsset,
uint80(_roundId)
);
// check that price timestamp is after latest timestamp the vault was updated at
require(
timestamp > _vaultLatestUpdate,
"MarginCalculator: auction timestamp should be post vault latest update"
);
// another struct to store some useful short otoken details, to avoid stack to deep error
ShortScaledDetails memory shortDetails = ShortScaledDetails({
shortAmount: FPI.fromScaledUint(_vault.shortAmounts[0], BASE),
shortStrike: FPI.fromScaledUint(vaultDetails.shortStrikePrice, BASE),
shortUnderlyingPrice: FPI.fromScaledUint(price, BASE)
});
bytes32 productHash = _getProductHash(
vaultDetails.shortUnderlyingAsset,
vaultDetails.shortStrikeAsset,
vaultDetails.shortCollateralAsset,
vaultDetails.isShortPut
);
// convert vault collateral to a fixed point (1e27) from collateral decimals
FPI.FixedPointInt memory depositedCollateral = FPI.fromScaledUint(
_vault.collateralAmounts[0],
vaultDetails.collateralDecimals
);
FPI.FixedPointInt memory collateralRequired = _getNakedMarginRequired(
productHash,
shortDetails.shortAmount,
shortDetails.shortUnderlyingPrice,
shortDetails.shortStrike,
vaultDetails.shortExpiryTimestamp,
vaultDetails.isShortPut
);
// if collateral required <= collateral in the vault, the vault is not liquidatable
if (collateralRequired.isLessThanOrEqual(depositedCollateral)) {
return (false, 0, 0);
}
FPI.FixedPointInt memory cashValue = _getCashValue(
shortDetails.shortStrike,
shortDetails.shortUnderlyingPrice,
vaultDetails.isShortPut
);
// get the amount of collateral per 1 repaid otoken
uint256 debtPrice = _getDebtPrice(
depositedCollateral,
shortDetails.shortAmount,
cashValue,
shortDetails.shortUnderlyingPrice,
timestamp,
vaultDetails.collateralDecimals,
vaultDetails.isShortPut
);
return (true, debtPrice, dust[vaultDetails.shortCollateralAsset]);
}
/**
* @notice calculate required collateral margin for a vault
* @param _vault theoretical vault that needs to be checked
* @param _vaultType vault type
* @return the vault collateral amount, and marginRequired the minimal amount of collateral needed in a vault, scaled to 1e27
*/
function getMarginRequired(MarginVault.Vault memory _vault, uint256 _vaultType)
external
view
returns (FPI.FixedPointInt memory, FPI.FixedPointInt memory)
{
VaultDetails memory vaultDetail = _getVaultDetails(_vault, _vaultType);
return _getMarginRequired(_vault, vaultDetail);
}
/**
* @notice returns the amount of collateral that can be removed from an actual or a theoretical vault
* @dev return amount is denominated in the collateral asset for the oToken in the vault, or the collateral asset in the vault
* @param _vault theoretical vault that needs to be checked
* @param _vaultType vault type (0 for spread/max loss, 1 for naked margin)
* @return excessCollateral the amount by which the margin is above or below the required amount
* @return isExcess True if there is excess margin in the vault, False if there is a deficit of margin in the vault
* if True, collateral can be taken out from the vault, if False, additional collateral needs to be added to vault
*/
function getExcessCollateral(MarginVault.Vault memory _vault, uint256 _vaultType)
public
view
returns (uint256, bool)
{
VaultDetails memory vaultDetails = _getVaultDetails(_vault, _vaultType);
// include all the checks for to ensure the vault is valid
_checkIsValidVault(_vault, vaultDetails);
// if the vault contains no oTokens, return the amount of collateral
if (!vaultDetails.hasShort && !vaultDetails.hasLong) {
uint256 amount = vaultDetails.hasCollateral ? _vault.collateralAmounts[0] : 0;
return (amount, true);
}
// get required margin, denominated in collateral, scaled in 1e27
(FPI.FixedPointInt memory collateralAmount, FPI.FixedPointInt memory collateralRequired) = _getMarginRequired(
_vault,
vaultDetails
);
FPI.FixedPointInt memory excessCollateral = collateralAmount.sub(collateralRequired);
bool isExcess = excessCollateral.isGreaterThanOrEqual(ZERO);
uint256 collateralDecimals = vaultDetails.hasLong
? vaultDetails.longCollateralDecimals
: vaultDetails.shortCollateralDecimals;
// if is excess, truncate the tailing digits in excessCollateralExternal calculation
uint256 excessCollateralExternal = excessCollateral.toScaledUint(collateralDecimals, isExcess);
return (excessCollateralExternal, isExcess);
}
/**
* @notice return the cash value of an expired oToken, denominated in strike asset
* @dev for a call, return Max (0, underlyingPriceInStrike - otoken.strikePrice)
* @dev for a put, return Max(0, otoken.strikePrice - underlyingPriceInStrike)
* @param _underlying otoken underlying asset
* @param _strike otoken strike asset
* @param _expiryTimestamp otoken expiry timestamp
* @param _strikePrice otoken strike price
* @param _strikePrice true if otoken is put otherwise false
* @return cash value of an expired otoken, denominated in the strike asset
*/
function _getExpiredCashValue(
address _underlying,
address _strike,
uint256 _expiryTimestamp,
uint256 _strikePrice,
bool _isPut
) internal view returns (FPI.FixedPointInt memory) {
// strike price is denominated in strike asset
FPI.FixedPointInt memory strikePrice = FPI.fromScaledUint(_strikePrice, BASE);
FPI.FixedPointInt memory one = FPI.fromScaledUint(1, 0);
// calculate the value of the underlying asset in terms of the strike asset
FPI.FixedPointInt memory underlyingPriceInStrike = _convertAmountOnExpiryPrice(
one, // underlying price is 1 (1e27) in term of underlying
_underlying,
_strike,
_expiryTimestamp
);
return _getCashValue(strikePrice, underlyingPriceInStrike, _isPut);
}
/// @dev added this struct to avoid stack-too-deep error
struct OtokenDetails {
address otokenUnderlyingAsset;
address otokenCollateralAsset;
address otokenStrikeAsset;
uint256 otokenExpiry;
bool isPut;
}
/**
* @notice calculate the amount of collateral needed for a vault
* @dev vault passed in has already passed the checkIsValidVault function
* @param _vault theoretical vault that needs to be checked
* @return the vault collateral amount, and marginRequired the minimal amount of collateral needed in a vault,
* scaled to 1e27
*/
function _getMarginRequired(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails)
internal
view
returns (FPI.FixedPointInt memory, FPI.FixedPointInt memory)
{
FPI.FixedPointInt memory shortAmount = _vaultDetails.hasShort
? FPI.fromScaledUint(_vault.shortAmounts[0], BASE)
: ZERO;
FPI.FixedPointInt memory longAmount = _vaultDetails.hasLong
? FPI.fromScaledUint(_vault.longAmounts[0], BASE)
: ZERO;
FPI.FixedPointInt memory collateralAmount = _vaultDetails.hasCollateral
? FPI.fromScaledUint(_vault.collateralAmounts[0], _vaultDetails.collateralDecimals)
: ZERO;
FPI.FixedPointInt memory shortStrike = _vaultDetails.hasShort
? FPI.fromScaledUint(_vaultDetails.shortStrikePrice, BASE)
: ZERO;
// struct to avoid stack too deep error
OtokenDetails memory otokenDetails = OtokenDetails(
_vaultDetails.hasShort ? _vaultDetails.shortUnderlyingAsset : _vaultDetails.longUnderlyingAsset,
_vaultDetails.hasShort ? _vaultDetails.shortCollateralAsset : _vaultDetails.longCollateralAsset,
_vaultDetails.hasShort ? _vaultDetails.shortStrikeAsset : _vaultDetails.longStrikeAsset,
_vaultDetails.hasShort ? _vaultDetails.shortExpiryTimestamp : _vaultDetails.longExpiryTimestamp,
_vaultDetails.hasShort ? _vaultDetails.isShortPut : _vaultDetails.isLongPut
);
if (now < otokenDetails.otokenExpiry) {
// it's not expired, return amount of margin required based on vault type
if (_vaultDetails.vaultType == 1) {
// this is a naked margin vault
// fetch dust amount for otoken collateral asset as FixedPointInt, assuming dust is already scaled by collateral decimals
FPI.FixedPointInt memory dustAmount = FPI.fromScaledUint(
dust[_vaultDetails.shortCollateralAsset],
_vaultDetails.collateralDecimals
);
// check that collateral deposited in naked margin vault is greater than dust amount for that particular collateral asset
if (collateralAmount.isGreaterThan(ZERO)) {
require(
collateralAmount.isGreaterThan(dustAmount),
"MarginCalculator: naked margin vault should have collateral amount greater than dust amount"
);
}
// get underlying asset price for short option
FPI.FixedPointInt memory shortUnderlyingPrice = FPI.fromScaledUint(
oracle.getPrice(_vaultDetails.shortUnderlyingAsset),
BASE
);
// encode product hash
bytes32 productHash = _getProductHash(
_vaultDetails.shortUnderlyingAsset,
_vaultDetails.shortStrikeAsset,
_vaultDetails.shortCollateralAsset,
_vaultDetails.isShortPut
);
// return amount of collateral in vault and needed collateral amount for margin
return (
collateralAmount,
_getNakedMarginRequired(
productHash,
shortAmount,
shortUnderlyingPrice,
shortStrike,
otokenDetails.otokenExpiry,
otokenDetails.isPut
)
);
} else {
// this is a fully collateralized vault
FPI.FixedPointInt memory longStrike = _vaultDetails.hasLong
? FPI.fromScaledUint(_vaultDetails.longStrikePrice, BASE)
: ZERO;
if (otokenDetails.isPut) {
FPI.FixedPointInt memory strikeNeeded = _getPutSpreadMarginRequired(
shortAmount,
longAmount,
shortStrike,
longStrike
);
// convert amount to be denominated in collateral
return (
collateralAmount,
_convertAmountOnLivePrice(
strikeNeeded,
otokenDetails.otokenStrikeAsset,
otokenDetails.otokenCollateralAsset
)
);
} else {
FPI.FixedPointInt memory underlyingNeeded = _getCallSpreadMarginRequired(
shortAmount,
longAmount,
shortStrike,
longStrike
);
// convert amount to be denominated in collateral
return (
collateralAmount,
_convertAmountOnLivePrice(
underlyingNeeded,
otokenDetails.otokenUnderlyingAsset,
otokenDetails.otokenCollateralAsset
)
);
}
}
} else {
// the vault has expired. calculate the cash value of all the minted short options
FPI.FixedPointInt memory shortCashValue = _vaultDetails.hasShort
? _getExpiredCashValue(
_vaultDetails.shortUnderlyingAsset,
_vaultDetails.shortStrikeAsset,
_vaultDetails.shortExpiryTimestamp,
_vaultDetails.shortStrikePrice,
otokenDetails.isPut
)
: ZERO;
FPI.FixedPointInt memory longCashValue = _vaultDetails.hasLong
? _getExpiredCashValue(
_vaultDetails.longUnderlyingAsset,
_vaultDetails.longStrikeAsset,
_vaultDetails.longExpiryTimestamp,
_vaultDetails.longStrikePrice,
otokenDetails.isPut
)
: ZERO;
FPI.FixedPointInt memory valueInStrike = _getExpiredSpreadCashValue(
shortAmount,
longAmount,
shortCashValue,
longCashValue
);
// convert amount to be denominated in collateral
return (
collateralAmount,
_convertAmountOnExpiryPrice(
valueInStrike,
otokenDetails.otokenStrikeAsset,
otokenDetails.otokenCollateralAsset,
otokenDetails.otokenExpiry
)
);
}
}
/**
* @notice get required collateral for naked margin position
* if put:
* a = min(strike price, spot shock * underlying price)
* b = max(strike price - spot shock * underlying price, 0)
* marginRequired = ( option upper bound value * a + b) * short amount
* if call:
* a = min(1, strike price / (underlying price / spot shock value))
* b = max(1- (strike price / (underlying price / spot shock value)), 0)
* marginRequired = (option upper bound value * a + b) * short amount
* @param _productHash product hash
* @param _shortAmount short amount in vault, in FixedPointInt type
* @param _strikePrice strike price of short otoken, in FixedPointInt type
* @param _underlyingPrice underlying price of short otoken underlying asset, in FixedPointInt type
* @param _shortExpiryTimestamp short otoken expiry timestamp
* @param _isPut otoken type, true if put option, false for call option
* @return required margin for this naked vault, in FixedPointInt type (scaled by 1e27)
*/
function _getNakedMarginRequired(
bytes32 _productHash,
FPI.FixedPointInt memory _shortAmount,
FPI.FixedPointInt memory _underlyingPrice,
FPI.FixedPointInt memory _strikePrice,
uint256 _shortExpiryTimestamp,
bool _isPut
) internal view returns (FPI.FixedPointInt memory) {
// find option upper bound value
FPI.FixedPointInt memory optionUpperBoundValue = _findUpperBoundValue(_productHash, _shortExpiryTimestamp);
// convert spot shock value of this product to FixedPointInt (already scaled by 1e27)
FPI.FixedPointInt memory spotShockValue = FPI.FixedPointInt(int256(spotShock[_productHash]));
FPI.FixedPointInt memory a;
FPI.FixedPointInt memory b;
FPI.FixedPointInt memory marginRequired;
if (_isPut) {
a = FPI.min(_strikePrice, spotShockValue.mul(_underlyingPrice));
b = FPI.max(_strikePrice.sub(spotShockValue.mul(_underlyingPrice)), ZERO);
marginRequired = optionUpperBoundValue.mul(a).add(b).mul(_shortAmount);
} else {
FPI.FixedPointInt memory one = FPI.fromScaledUint(1e27, SCALING_FACTOR);
a = FPI.min(one, _strikePrice.mul(spotShockValue).div(_underlyingPrice));
b = FPI.max(one.sub(_strikePrice.mul(spotShockValue).div(_underlyingPrice)), ZERO);
marginRequired = optionUpperBoundValue.mul(a).add(b).mul(_shortAmount);
}
return marginRequired;
}
/**
* @notice find upper bound value for product by specific expiry timestamp
* @dev should return the upper bound value that correspond to option time to expiry, of if not found should return the next greater one, revert if no value found
* @param _productHash product hash
* @param _expiryTimestamp expiry timestamp
* @return option upper bound value
*/
function _findUpperBoundValue(bytes32 _productHash, uint256 _expiryTimestamp)
internal
view
returns (FPI.FixedPointInt memory)
{
// get time to expiry array of this product hash
uint256[] memory timesToExpiry = timesToExpiryForProduct[_productHash];
// check that this product have upper bound values stored
require(timesToExpiry.length != 0, "MarginCalculator: product have no expiry values");
uint256 optionTimeToExpiry = _expiryTimestamp.sub(now);
// check that the option time to expiry is in the expiry array
require(
timesToExpiry[timesToExpiry.length.sub(1)] >= optionTimeToExpiry,
"MarginCalculator: product have no upper bound value"
);
// loop through the array and return the upper bound value in FixedPointInt type (already scaled by 1e27)
for (uint8 i = 0; i < timesToExpiry.length; i++) {
if (timesToExpiry[i] >= optionTimeToExpiry)
return FPI.fromScaledUint(maxPriceAtTimeToExpiry[_productHash][timesToExpiry[i]], SCALING_FACTOR);
}
}
/**
* @dev returns the strike asset amount of margin required for a put or put spread with the given short oTokens, long oTokens and amounts
*
* marginRequired = max( (short amount * short strike) - (long strike * min (short amount, long amount)) , 0 )
*
* @return margin requirement denominated in the strike asset
*/
function _getPutSpreadMarginRequired(
FPI.FixedPointInt memory _shortAmount,
FPI.FixedPointInt memory _longAmount,
FPI.FixedPointInt memory _shortStrike,
FPI.FixedPointInt memory _longStrike
) internal view returns (FPI.FixedPointInt memory) {
return FPI.max(_shortAmount.mul(_shortStrike).sub(_longStrike.mul(FPI.min(_shortAmount, _longAmount))), ZERO);
}
/**
* @dev returns the underlying asset amount required for a call or call spread with the given short oTokens, long oTokens, and amounts
*
* (long strike - short strike) * short amount
* marginRequired = max( ------------------------------------------------- , max (short amount - long amount, 0) )
* long strike
*
* @dev if long strike = 0, return max( short amount - long amount, 0)
* @return margin requirement denominated in the underlying asset
*/
function _getCallSpreadMarginRequired(
FPI.FixedPointInt memory _shortAmount,
FPI.FixedPointInt memory _longAmount,
FPI.FixedPointInt memory _shortStrike,
FPI.FixedPointInt memory _longStrike
) internal view returns (FPI.FixedPointInt memory) {
// max (short amount - long amount , 0)
if (_longStrike.isEqual(ZERO)) {
return FPI.max(_shortAmount.sub(_longAmount), ZERO);
}
/**
* (long strike - short strike) * short amount
* calculate ----------------------------------------------
* long strike
*/
FPI.FixedPointInt memory firstPart = _longStrike.sub(_shortStrike).mul(_shortAmount).div(_longStrike);
/**
* calculate max ( short amount - long amount , 0)
*/
FPI.FixedPointInt memory secondPart = FPI.max(_shortAmount.sub(_longAmount), ZERO);
return FPI.max(firstPart, secondPart);
}
/**
* @notice convert an amount in asset A to equivalent amount of asset B, based on a live price
* @dev function includes the amount and applies .mul() first to increase the accuracy
* @param _amount amount in asset A
* @param _assetA asset A
* @param _assetB asset B
* @return _amount in asset B
*/
function _convertAmountOnLivePrice(
FPI.FixedPointInt memory _amount,
address _assetA,
address _assetB
) internal view returns (FPI.FixedPointInt memory) {
if (_assetA == _assetB) {
return _amount;
}
uint256 priceA = oracle.getPrice(_assetA);
uint256 priceB = oracle.getPrice(_assetB);
// amount A * price A in USD = amount B * price B in USD
// amount B = amount A * price A / price B
return _amount.mul(FPI.fromScaledUint(priceA, BASE)).div(FPI.fromScaledUint(priceB, BASE));
}
/**
* @notice convert an amount in asset A to equivalent amount of asset B, based on an expiry price
* @dev function includes the amount and apply .mul() first to increase the accuracy
* @param _amount amount in asset A
* @param _assetA asset A
* @param _assetB asset B
* @return _amount in asset B
*/
function _convertAmountOnExpiryPrice(
FPI.FixedPointInt memory _amount,
address _assetA,
address _assetB,
uint256 _expiry
) internal view returns (FPI.FixedPointInt memory) {
if (_assetA == _assetB) {
return _amount;
}
(uint256 priceA, bool priceAFinalized) = oracle.getExpiryPrice(_assetA, _expiry);
(uint256 priceB, bool priceBFinalized) = oracle.getExpiryPrice(_assetB, _expiry);
require(priceAFinalized && priceBFinalized, "MarginCalculator: price at expiry not finalized yet");
// amount A * price A in USD = amount B * price B in USD
// amount B = amount A * price A / price B
return _amount.mul(FPI.fromScaledUint(priceA, BASE)).div(FPI.fromScaledUint(priceB, BASE));
}
/**
* @notice return debt price, how much collateral asset per 1 otoken repaid in collateral decimal
* ending price = vault collateral / vault debt
* if auction ended, return ending price
* else calculate starting price
* for put option:
* starting price = max(cash value - underlying price * oracle deviation, 0)
* for call option:
* max(cash value - underlying price * oracle deviation, 0)
* starting price = ---------------------------------------------------------------
* underlying price
*
*
* starting price + (ending price - starting price) * auction elapsed time
* then price = --------------------------------------------------------------------------
* auction time
*
*
* @param _vaultCollateral vault collateral amount
* @param _vaultDebt vault short amount
* @param _cashValue option cash value
* @param _spotPrice option underlying asset price (in USDC)
* @param _auctionStartingTime auction starting timestamp (_spotPrice timestamp from chainlink)
* @param _collateralDecimals collateral asset decimals
* @param _isPut otoken type, true for put, false for call option
* @return price of 1 debt otoken in collateral asset scaled by collateral decimals
*/
function _getDebtPrice(
FPI.FixedPointInt memory _vaultCollateral,
FPI.FixedPointInt memory _vaultDebt,
FPI.FixedPointInt memory _cashValue,
FPI.FixedPointInt memory _spotPrice,
uint256 _auctionStartingTime,
uint256 _collateralDecimals,
bool _isPut
) internal view returns (uint256) {
// price of 1 repaid otoken in collateral asset, scaled to 1e27
FPI.FixedPointInt memory price;
// auction ending price
FPI.FixedPointInt memory endingPrice = _vaultCollateral.div(_vaultDebt);
// auction elapsed time
uint256 auctionElapsedTime = now.sub(_auctionStartingTime);
// if auction ended, return ending price
if (auctionElapsedTime >= AUCTION_TIME) {
price = endingPrice;
} else {
// starting price
FPI.FixedPointInt memory startingPrice;
{
// store oracle deviation in a FixedPointInt (already scaled by 1e27)
FPI.FixedPointInt memory fixedOracleDeviation = FPI.fromScaledUint(oracleDeviation, SCALING_FACTOR);
if (_isPut) {
startingPrice = FPI.max(_cashValue.sub(fixedOracleDeviation.mul(_spotPrice)), ZERO);
} else {
startingPrice = FPI.max(_cashValue.sub(fixedOracleDeviation.mul(_spotPrice)), ZERO).div(_spotPrice);
}
}
// store auctionElapsedTime in a FixedPointInt scaled by 1e27
FPI.FixedPointInt memory auctionElapsedTimeFixedPoint = FPI.fromScaledUint(auctionElapsedTime, 18);
// store AUCTION_TIME in a FixedPointInt (already scaled by 1e27)
FPI.FixedPointInt memory auctionTime = FPI.fromScaledUint(AUCTION_TIME, 18);
// calculate price of 1 repaid otoken, scaled by the collateral decimals, expilictly rounded down
price = startingPrice.add(
(endingPrice.sub(startingPrice)).mul(auctionElapsedTimeFixedPoint).div(auctionTime)
);
// cap liquidation price to ending price
if (price.isGreaterThan(endingPrice)) price = endingPrice;
}
return price.toScaledUint(_collateralDecimals, true);
}
/**
* @notice get vault details to save us from making multiple external calls
* @param _vault vault struct
* @param _vaultType vault type, 0 for max loss/spreads and 1 for naked margin vault
* @return vault details in VaultDetails struct
*/
function _getVaultDetails(MarginVault.Vault memory _vault, uint256 _vaultType)
internal
view
returns (VaultDetails memory)
{
VaultDetails memory vaultDetails = VaultDetails(
address(0),
address(0),
address(0),
address(0),
address(0),
address(0),
0,
0,
0,
0,
0,
0,
0,
0,
false,
false,
false,
false,
false
);
// check if vault has long, short otoken and collateral asset
vaultDetails.hasLong = _isNotEmpty(_vault.longOtokens);
vaultDetails.hasShort = _isNotEmpty(_vault.shortOtokens);
vaultDetails.hasCollateral = _isNotEmpty(_vault.collateralAssets);
vaultDetails.vaultType = _vaultType;
// get vault long otoken if available
if (vaultDetails.hasLong) {
OtokenInterface long = OtokenInterface(_vault.longOtokens[0]);
(
vaultDetails.longCollateralAsset,
vaultDetails.longUnderlyingAsset,
vaultDetails.longStrikeAsset,
vaultDetails.longStrikePrice,
vaultDetails.longExpiryTimestamp,
vaultDetails.isLongPut
) = _getOtokenDetails(address(long));
vaultDetails.longCollateralDecimals = uint256(ERC20Interface(vaultDetails.longCollateralAsset).decimals());
}
// get vault short otoken if available
if (vaultDetails.hasShort) {
OtokenInterface short = OtokenInterface(_vault.shortOtokens[0]);
(
vaultDetails.shortCollateralAsset,
vaultDetails.shortUnderlyingAsset,
vaultDetails.shortStrikeAsset,
vaultDetails.shortStrikePrice,
vaultDetails.shortExpiryTimestamp,
vaultDetails.isShortPut
) = _getOtokenDetails(address(short));
vaultDetails.shortCollateralDecimals = uint256(
ERC20Interface(vaultDetails.shortCollateralAsset).decimals()
);
}
if (vaultDetails.hasCollateral) {
vaultDetails.collateralDecimals = uint256(ERC20Interface(_vault.collateralAssets[0]).decimals());
}
return vaultDetails;
}
/**
* @dev calculate the cash value obligation for an expired vault, where a positive number is an obligation
*
* Formula: net = (short cash value * short amount) - ( long cash value * long Amount )
*
* @return cash value obligation denominated in the strike asset
*/
function _getExpiredSpreadCashValue(
FPI.FixedPointInt memory _shortAmount,
FPI.FixedPointInt memory _longAmount,
FPI.FixedPointInt memory _shortCashValue,
FPI.FixedPointInt memory _longCashValue
) internal pure returns (FPI.FixedPointInt memory) {
return _shortCashValue.mul(_shortAmount).sub(_longCashValue.mul(_longAmount));
}
/**
* @dev check if asset array contain a token address
* @return True if the array is not empty
*/
function _isNotEmpty(address[] memory _assets) internal pure returns (bool) {
return _assets.length > 0 && _assets[0] != address(0);
}
/**
* @dev ensure that:
* a) at most 1 asset type used as collateral
* b) at most 1 series of option used as the long option
* c) at most 1 series of option used as the short option
* d) asset array lengths match for long, short and collateral
* e) long option and collateral asset is acceptable for margin with short asset
* @param _vault the vault to check
* @param _vaultDetails vault details struct
*/
function _checkIsValidVault(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails) internal pure {
// ensure all the arrays in the vault are valid
require(_vault.shortOtokens.length <= 1, "MarginCalculator: Too many short otokens in the vault");
require(_vault.longOtokens.length <= 1, "MarginCalculator: Too many long otokens in the vault");
require(_vault.collateralAssets.length <= 1, "MarginCalculator: Too many collateral assets in the vault");
require(
_vault.shortOtokens.length == _vault.shortAmounts.length,
"MarginCalculator: Short asset and amount mismatch"
);
require(
_vault.longOtokens.length == _vault.longAmounts.length,
"MarginCalculator: Long asset and amount mismatch"
);
require(
_vault.collateralAssets.length == _vault.collateralAmounts.length,
"MarginCalculator: Collateral asset and amount mismatch"
);
// ensure the long asset is valid for the short asset
require(
_isMarginableLong(_vault, _vaultDetails),
"MarginCalculator: long asset not marginable for short asset"
);
// ensure that the collateral asset is valid for the short asset
require(
_isMarginableCollateral(_vault, _vaultDetails),
"MarginCalculator: collateral asset not marginable for short asset"
);
}
/**
* @dev if there is a short option and a long option in the vault, ensure that the long option is able to be used as collateral for the short option
* @param _vault the vault to check
* @param _vaultDetails vault details struct
* @return true if long is marginable or false if not
*/
function _isMarginableLong(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails)
internal
pure
returns (bool)
{
if (_vaultDetails.vaultType == 1)
require(!_vaultDetails.hasLong, "MarginCalculator: naked margin vault cannot have long otoken");
// if vault is missing a long or a short, return True
if (!_vaultDetails.hasLong || !_vaultDetails.hasShort) return true;
return
_vault.longOtokens[0] != _vault.shortOtokens[0] &&
_vaultDetails.longUnderlyingAsset == _vaultDetails.shortUnderlyingAsset &&
_vaultDetails.longStrikeAsset == _vaultDetails.shortStrikeAsset &&
_vaultDetails.longCollateralAsset == _vaultDetails.shortCollateralAsset &&
_vaultDetails.longExpiryTimestamp == _vaultDetails.shortExpiryTimestamp &&
_vaultDetails.isLongPut == _vaultDetails.isShortPut;
}
/**
* @dev if there is short option and collateral asset in the vault, ensure that the collateral asset is valid for the short option
* @param _vault the vault to check
* @param _vaultDetails vault details struct
* @return true if marginable or false
*/
function _isMarginableCollateral(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails)
internal
pure
returns (bool)
{
bool isMarginable = true;
if (!_vaultDetails.hasCollateral) return isMarginable;
if (_vaultDetails.hasShort) {
isMarginable = _vaultDetails.shortCollateralAsset == _vault.collateralAssets[0];
} else if (_vaultDetails.hasLong) {
isMarginable = _vaultDetails.longCollateralAsset == _vault.collateralAssets[0];
}
return isMarginable;
}
/**
* @notice get a product hash
* @param _underlying option underlying asset
* @param _strike option strike asset
* @param _collateral option collateral asset
* @param _isPut option type
* @return product hash
*/
function _getProductHash(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) internal pure returns (bytes32) {
return keccak256(abi.encode(_underlying, _strike, _collateral, _isPut));
}
/**
* @notice get option cash value
* @dev this assume that the underlying price is denominated in strike asset
* cash value = max(underlying price - strike price, 0)
* @param _strikePrice option strike price
* @param _underlyingPrice option underlying price
* @param _isPut option type, true for put and false for call option
*/
function _getCashValue(
FPI.FixedPointInt memory _strikePrice,
FPI.FixedPointInt memory _underlyingPrice,
bool _isPut
) internal view returns (FPI.FixedPointInt memory) {
if (_isPut) return _strikePrice.isGreaterThan(_underlyingPrice) ? _strikePrice.sub(_underlyingPrice) : ZERO;
return _underlyingPrice.isGreaterThan(_strikePrice) ? _underlyingPrice.sub(_strikePrice) : ZERO;
}
/**
* @dev get otoken detail, from both otoken versions
*/
function _getOtokenDetails(address _otoken)
internal
view
returns (
address,
address,
address,
uint256,
uint256,
bool
)
{
OtokenInterface otoken = OtokenInterface(_otoken);
try otoken.getOtokenDetails() returns (
address collateral,
address underlying,
address strike,
uint256 strikePrice,
uint256 expiry,
bool isPut
) {
return (collateral, underlying, strike, strikePrice, expiry, isPut);
} catch {
// v1 otoken
return (
otoken.collateralAsset(),
otoken.underlyingAsset(),
otoken.strikeAsset(),
otoken.strikePrice(),
otoken.expiryTimestamp(),
otoken.isPut()
);
}
}
} | returns the strike asset amount of margin required for a put or put spread with the given short oTokens, long oTokens and amounts marginRequired = max( (short amount short strike) - (long strike min (short amount, long amount)) , 0 ) return margin requirement denominated in the strike asset/ | function _getPutSpreadMarginRequired(
FPI.FixedPointInt memory _shortAmount,
FPI.FixedPointInt memory _longAmount,
FPI.FixedPointInt memory _shortStrike,
FPI.FixedPointInt memory _longStrike
) internal view returns (FPI.FixedPointInt memory) {
return FPI.max(_shortAmount.mul(_shortStrike).sub(_longStrike.mul(FPI.min(_shortAmount, _longAmount))), ZERO);
}
| 1,551,745 |
//SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 < 0.9.0;
pragma experimental ABIEncoderV2; //Abiencoder es para calcular hashes
//Candidato // EDAD // ID
// TONI // 20 // 201
// Alberto // 35 // 203
// Mirta // 21 // 201
// Pato // 26 // 001
contract votacion {
//Direccion del propietario del contrato.
address public owner;
//Relacion entre el nombre y el hash de sus datos personales.
mapping(string => bytes32) ID_Candidato;
//Relacion entre el nombre del candidato y el numero de votos.
mapping(string => uint) votos_Candidato;
//Lista para almacenar los nombres de los candidatos.
string[] candidatos;
//Lista de los hashes de la identidad de los votantes. Con validacion, usamos bytes32 para mantener el anonimato.
bytes32[] votantes;
//Constructor
constructor () public {
owner = msg.sender;
}
//Funcion que te permite presentarte como candidato.
//Memory, fuerza a que la variable se elimine una ves la funcion finalice.
function Representar(string memory _nombrePersona,uint _edadPersona, string memory _idPersona) public {
//hash de los datos del candidato.
bytes32 hash_Candidato = keccak256(abi.encodePacked(_nombrePersona, _edadPersona, _idPersona));
//almacenar el hash de los datos del candidato que estan ligados a su nombre
ID_Candidato[_nombrePersona] = hash_Candidato;
//Actualizamos la lista de los candidatos.
candidatos.push(_nombrePersona);
}
//Esta funcion nos permite ver el vector de candidatos. String es un vector de nombres.
function verCandidatos() public view returns(string[] memory){
//Devuelve la lista de los candidatos presentados
return candidatos;
}
//Los votatantes usaran esta funcion para elegir a su candidato y votarlo
function votar(string memory _candidato) public {
//hash de la direccion de la persona que ejecuta esta funcion
bytes32 hash_Votante = keccak256(abi.encodePacked(msg.sender));
//verificamos si el votante ya a votado.
for(uint i= 0; i < votantes.length; i++){
require(votantes[i] != hash_Votante, "Ya votaste" );
}
//Almacenamos el hash del votante deltro del array de votantes
votantes.push(hash_Votante);
//Añadimos un voto al candidato seleccinado
votos_Candidato[_candidato]++;
}
//La cantidad de votos que tiene uun candidato.
function verVotos(string memory _nombreCandidato) public view returns(uint){
return votos_Candidato[_nombreCandidato];
}
//Funcion auxiliar que transforma un uint a un string
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
//Ver los votos de cada uno de los candidatos.
function VerResultados() public view returns(string[] memory){
//guardamos en una variable los string los candidatos con sus respectivos votos
string memory resultados;
//Recorremos el array de candidatos para actualizar el string resultados
for(uint i=0; i < candidatos.length; i++ ){
//transformacion de bytes a string.
//Actualizamos el string resultados, y añadimos el candidato que ocupa la posicion "i" del array candidatos
// y su numero de votoss
resultados = string(abi.encodePacked(resultados,"C", candidatos[i], " ,", uint2str(verVotos(candidatos[i])), ")" ));
}
//devolvemos los resultados.
return resultados;
}
//Proporcionar el nombre del candidato ganador
function Ganador() public view returns(string memory){
//la variable ganador va a contener el nombre del candidato ganador.
string memory ganador = candidatos[0];
//variable flag para empate
bool flag;
//recorremos el array de candidatos para determinar el candidato con un numero mayor de votos
for(uint i=1; i < candidatos.length; i++ ){
//comparamos si nuestro ganador ha sido superado por otro candidato.
if( votos_Candidato[candidatos[i]] > votos_candidato[ganador]){
ganador= candidatos[i];
flag=false;
}else {
//miramos si hay empate entre los candidatos
if(votos_Candidato[candidatos[i]] == votos_candidato[ganador]){
flag=true;
}
}
}
//comprobamos si ha habido un empate entre los candidatos
if (flag==true){
ganador = "hay un empate entre los candiadatos";
}
//devolvemos el ganador
return ganador;
}
} | Proporcionar el nombre del candidato ganadorla variable ganador va a contener el nombre del candidato ganador.variable flag para empaterecorremos el array de candidatos para determinar el candidato con un numero mayor de votoscomparamos si nuestro ganador ha sido superado por otro candidato.miramos si hay empate entre los candidatoscomprobamos si ha habido un empate entre los candidatos | function Ganador() public view returns(string memory){
string memory ganador = candidatos[0];
bool flag;
for(uint i=1; i < candidatos.length; i++ ){
if( votos_Candidato[candidatos[i]] > votos_candidato[ganador]){
ganador= candidatos[i];
flag=false;
if(votos_Candidato[candidatos[i]] == votos_candidato[ganador]){
flag=true;
}
}
}
if (flag==true){
ganador = "hay un empate entre los candiadatos";
}
}
| 1,086,243 |
./full_match/44787/0xD49f832Ec694AA7DB2b122d5Ed14FC4FC523Cdc5/sources/contracts/JustArtMarket.sol | returns marketfee percentage | function getMarketFee() external view returns (uint256) {
return marketFeePercentage;
}
| 13,290,983 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/// @author jpegmint.xyz
import "./IRoyaltiesERC2981.sol";
import "./IRoyaltiesManifold.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
abstract contract ERC721RoyaltiesUpgradeable is Initializable, ERC721Upgradeable, IRoyaltiesERC2981, IRoyaltiesManifold {
address private _royaltiesRecipient;
uint256 private _royaltiesBasisPoints;
function __ERC721Royalties_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Royalties_init_unchained();
}
function __ERC721Royalties_init_unchained() internal initializer {
}
/**
* @dev see {IERC165-supportsInterface}
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IRoyaltiesERC2981).interfaceId ||
interfaceId == type(IRoyaltiesManifold).interfaceId ||
super.supportsInterface(interfaceId)
;
}
/**
* @dev See {IRoyaltiesERC2981-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value) external view override returns (address, uint256) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IRoyaltiesCreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId) external view override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev Override with access control to set royalties.
*/
function setRoyalties(address recipient, uint256 basisPoints) external virtual;
/**
* @dev Set contract-wide royalties.
*/
function _setRoyalties(address recipient, uint256 basisPoints) internal {
require(basisPoints <= 10000, 'Royalties: Too high');
_royaltiesRecipient = recipient;
_royaltiesBasisPoints = basisPoints;
}
/**
* @dev Calculates royalties using contract-wide setting.
*/
function _getRoyaltyInfo(uint256, uint256 value) internal view returns (address, uint256) {
uint256 royaltyAmount = (value * _royaltiesBasisPoints) / 10000;
return (_royaltiesRecipient, royaltyAmount);
}
/**
* @dev Returns contract-wide royalties.
*/
function _getRoyalties(uint256) internal view returns (address payable[] memory, uint256[] memory) {
uint256[] memory royaltyBasisPoints = new uint[](1);
address payable[] memory royaltyReceivers = new address payable[](1);
royaltyBasisPoints[0] = _royaltiesBasisPoints;
royaltyReceivers[0] = payable(_royaltiesRecipient);
return (royaltyReceivers, royaltyBasisPoints);
}
}
| Returns contract-wide royalties./ | function _getRoyalties(uint256) internal view returns (address payable[] memory, uint256[] memory) {
uint256[] memory royaltyBasisPoints = new uint[](1);
address payable[] memory royaltyReceivers = new address payable[](1);
royaltyBasisPoints[0] = _royaltiesBasisPoints;
royaltyReceivers[0] = payable(_royaltiesRecipient);
return (royaltyReceivers, royaltyBasisPoints);
}
| 12,667,335 |
./partial_match/1/0xd5be7b469B99a612A8c01084616a70f0d30d462D/sources/MikuruAsakura.sol | 设置预售期间每个地址的最大 Mint 数量/ | function setOnPreSalesMintCountForAddress(
uint256 _onPreSalesMintCountForAddress
) external onlyOwner {
onPreSalesMintCountForAddress = _onPreSalesMintCountForAddress;
}
| 16,086,045 |
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../token/ITokenContract.sol";
/**
* @dev Supports ERC20 tokens
* The escrow smart contract for the open bazaar trades in Ethereum
* The smart contract is desgined keeping in mind the current wallet interface of the OB-core
* https://github.com/OpenBazaar/wallet-interface/blob/master/wallet.go
* Current wallet interface strictly adheres to UTXO(bitcoin) model
*/
contract Escrow_v1_0 {
using SafeMath for uint256;
enum Status {FUNDED, RELEASED}
enum TransactionType {ETHER, TOKEN}
event Executed(
bytes32 scriptHash,
address[] destinations,
uint256[] amounts
);
event FundAdded(
bytes32 scriptHash,
address indexed from,
uint256 valueAdded
);
event Funded(bytes32 scriptHash, address indexed from, uint256 value);
struct Transaction {
bytes32 scriptHash;//This is unique indentifier for a transaction
uint256 value;
uint256 lastModified;//Time at which transaction was last modified
Status status;
TransactionType transactionType;
uint8 threshold;
uint32 timeoutHours;
address buyer;
address seller;
address tokenAddress;// Token address in case of token transfer
address moderator;
mapping(address=>bool) isOwner;//to keep track of owners/signers.
mapping(address=>bool) voted;//to keep track of who all voted
mapping(address=>bool) beneficiaries;//Benefeciaries of execution
}
mapping(bytes32 => Transaction) public transactions;
uint256 public transactionCount = 0;
//Contains mapping between each party and all of his transactions
mapping(address => bytes32[])public partyVsTransaction;
modifier transactionExists(bytes32 scriptHash) {
require(
transactions[scriptHash].value != 0, "Transaction does not exists"
);
_;
}
modifier transactionDoesNotExists (bytes32 scriptHash) {
require(transactions[scriptHash].value == 0, "Transaction exists");
_;
}
modifier inFundedState(bytes32 scriptHash) {
require(
transactions[scriptHash].status == Status.FUNDED, "Transaction is either in dispute or released state"
);
_;
}
modifier nonZeroAddress(address addressToCheck) {
require(addressToCheck != address(0), "Zero address passed");
_;
}
modifier checkTransactionType(
bytes32 scriptHash,
TransactionType transactionType
)
{
require(
transactions[scriptHash].transactionType == transactionType, "Transaction type does not match"
);
_;
}
modifier onlyBuyer(bytes32 scriptHash) {
require(
msg.sender == transactions[scriptHash].buyer, "The initiator of the transaction is not buyer"
);
_;
}
/**
*@dev Add new transaction in the contract
*@param buyer The buyer of the transaction
*@param seller The seller of the listing associated with the transaction
*@param moderator Moderator for this transaction
*@param scriptHash keccak256 hash of the redeem script
*@param threshold Minimum number of singatures required to released funds
*@param timeoutHours Hours after which seller can release funds into his favour by signing transaction
*@param uniqueId bytes20 unique id for the transaction, generated by ETH wallet
*Redeem Script format will be following
<uniqueId: 20><threshold:1><timeoutHours:4><buyer:20><seller:20><moderator:20><multisigAddress:20>
* scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator)
*Pass amount of the ethers to be put in escrow
*Please keep in mind you will have to add moderator fees also in the value
*/
function addTransaction(
address buyer,
address seller,
address moderator,
uint8 threshold,
uint32 timeoutHours,
bytes32 scriptHash,
bytes20 uniqueId
)
external
payable
transactionDoesNotExists(scriptHash)
nonZeroAddress(buyer)
nonZeroAddress(seller)
{
_addTransaction(
buyer,
seller,
moderator,
threshold,
timeoutHours,
scriptHash,
msg.value,
uniqueId,
TransactionType.ETHER,
address(0)
);
emit Funded(scriptHash, msg.sender, msg.value);
}
/**
*@dev Add new transaction in the contract
*@param buyer The buyer of the transaction
*@param seller The seller of the listing associated with the transaction
*@param moderator Moderator for this transaction
*@param scriptHash keccak256 hash of the redeem script
*@param threshold Minimum number of singatures required to released funds
*@param timeoutHours Hours after which seller can release funds into his favour by signing transaction
*@param value Amount of tokens to be put in escrow
*@param uniqueId bytes20 unique id for the transaction, generated by ETH wallet
*@param tokenAddress Address of the token to be used
*Redeem Script format will be following
<uniqueId: 20><threshold:1><timeoutHours:4><buyer:20><seller:20><moderator:20><multisigAddress:20><tokenAddress:20>
* scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress)
*approve escrow contract to spend amount of token on your behalf
*Please keep in mind you will have to add moderator fees also in the value
*/
function addTokenTransaction(
address buyer,
address seller,
address moderator,
uint8 threshold,
uint32 timeoutHours,
bytes32 scriptHash,
uint256 value,
bytes20 uniqueId,
address tokenAddress
)
external
transactionDoesNotExists(scriptHash)
nonZeroAddress(buyer)
nonZeroAddress(seller)
nonZeroAddress(tokenAddress)
{
_addTransaction(
buyer,
seller,
moderator,
threshold,
timeoutHours,
scriptHash,
value,
uniqueId,
TransactionType.TOKEN,
tokenAddress
);
ITokenContract token = ITokenContract(tokenAddress);
require(
token.transferFrom(msg.sender, this, value),
"Token transfer failed, maybe you did not approve escrow contract to spend on behalf of buyer"
);
emit Funded(scriptHash, msg.sender, value);
}
/**
* @dev Check whether given address was a beneficiary of transaction execution or not
* @param scriptHash script hash of the transaction
* @param beneficiary Beneficiary address to be checked
*/
function checkBeneficiary(
bytes32 scriptHash,
address beneficiary
)
external
view
returns (bool check)
{
check = transactions[scriptHash].beneficiaries[beneficiary];
}
/**
* @dev Check whether given party has voted or not
* @param scriptHash script hash of the transaction
* @param party Address of the party whose vote has to be checked
* @return bool vote
*/
function checkVote(
bytes32 scriptHash,
address party
)
external
view
returns (bool vote)
{
vote = transactions[scriptHash].voted[party];
}
/**
*@dev Allows buyer of the transaction to add more funds(ether) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required
*@param scriptHash script hash of the transaction
* Only buyer of the transaction can invoke this method
*/
function addFundsToTransaction(
bytes32 scriptHash
)
external
transactionExists(scriptHash)
inFundedState(scriptHash)
checkTransactionType(scriptHash, TransactionType.ETHER)
onlyBuyer(scriptHash)
payable
{
uint256 _value = msg.value;
require(_value > 0, "Value must be greater than zero.");
transactions[scriptHash].value = transactions[scriptHash].value
.add(_value);
transactions[scriptHash].lastModified = block.timestamp;
emit FundAdded(scriptHash, msg.sender, _value);
}
/**
*@dev Allows buyer of the transaction to add more funds(Tokens) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required
*@param scriptHash script hash of the transaction
*/
function addTokensToTransaction(
bytes32 scriptHash,
uint256 value
)
external
transactionExists(scriptHash)
inFundedState(scriptHash)
checkTransactionType(scriptHash, TransactionType.TOKEN)
onlyBuyer(scriptHash)
{
uint256 _value = value;
require(_value > 0, "Value must be greater than zero.");
ITokenContract token = ITokenContract(
transactions[scriptHash].tokenAddress
);
require(
token.transferFrom(transactions[scriptHash].buyer, this, value),
"Token transfer failed, maybe you did not approve escrow contract to spend on behalf of buyer"
);
transactions[scriptHash].value = transactions[scriptHash].value
.add(_value);
transactions[scriptHash].lastModified = block.timestamp;
emit FundAdded(scriptHash, msg.sender, _value);
}
/**
*@dev Returns all transaction ids for a party
*@param partyAddress Address of the party
*/
function getAllTransactionsForParty(
address partyAddress
)
external
view
returns (bytes32[] scriptHashes)
{
return partyVsTransaction[partyAddress];
}
/**
*@dev Allows one of the moderator to collect all the signature to solve dispute and submit it to this method.
* If all the required signatures are collected and consensus has been reached than funds will be released to the voted party
*@param sigV Array containing V component of all the signatures
*@param sigR Array containing R component of all the signatures
*@param signS Array containing S component of all the signatures
*@param scriptHash script hash of the transaction
*@param destinations address of the destination in whose favour dispute resolution is taking place. In case of split payments it will be address of the split payments contract
*@param amounts value to send to each destination
*/
function execute(
uint8[] sigV,
bytes32[] sigR,
bytes32[] sigS,
bytes32 scriptHash,
address[] destinations,
uint256[] amounts
)
external
transactionExists(scriptHash)
inFundedState(scriptHash)
{
require(
destinations.length>0 && destinations.length == amounts.length, "Length of destinations is incorrect."
);
verifyTransaction(
sigV,
sigR,
sigS,
scriptHash,
destinations,
amounts
);
transactions[scriptHash].status = Status.RELEASED;
//Last modified timestamp modified, which will be used by rewards
transactions[scriptHash].lastModified = block.timestamp;
require(
transferFunds(scriptHash, destinations, amounts) == transactions[scriptHash].value,
"Total value to be released must be equal to the transaction escrow value"
);
emit Executed(scriptHash, destinations, amounts);
}
/**
*@dev Method for calculating script hash. Calculation will depend upon the type of transaction
* ETHER Type transaction-:
* Script Hash- keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator)
* TOKEN Type transaction
* Script Hash- keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress)
* Client can use this method to verify whether it has calculated correct script hash or not
*/
function calculateRedeemScriptHash(
bytes20 uniqueId,
uint8 threshold,
uint32 timeoutHours,
address buyer,
address seller,
address moderator,
address tokenAddress
)
public
view
returns (bytes32 hash)
{
if (tokenAddress == address(0)) {
hash = keccak256(
abi.encodePacked(
uniqueId,
threshold,
timeoutHours,
buyer,
seller,
moderator,
this
)
);
} else {
hash = keccak256(
abi.encodePacked(
uniqueId,
threshold,
timeoutHours,
buyer,
seller,
moderator,
this,
tokenAddress
)
);
}
}
/**
* @dev This methods checks validity of transaction
* 1. Verify Signatures
* 2. Check if minimum number of signatures has been acquired
* 3. If above condition is false, check if time lock is expired and the execution is signed by seller
*/
function verifyTransaction(
uint8[] sigV,
bytes32[] sigR,
bytes32[] sigS,
bytes32 scriptHash,
address[] destinations,
uint256[] amounts
)
private
{
address lastRecovered = verifySignatures(
sigV,
sigR,
sigS,
scriptHash,
destinations,
amounts
);
bool timeLockExpired = isTimeLockExpired(
transactions[scriptHash].timeoutHours,
transactions[scriptHash].lastModified
);
//if Minimum number of signatures are not gathered and timelock has not expired or transaction was not signed by seller then revert
if (
sigV.length < transactions[scriptHash].threshold && (!timeLockExpired || lastRecovered != transactions[scriptHash].seller)
)
{
revert("sigV.length is under the threshold.");
}
}
/**
*@dev Private method to transfer funds to the destination addresses on the basis of transaction type
*/
function transferFunds(
bytes32 scriptHash,
address[]destinations,
uint256[]amounts
)
private
returns (uint256 valueTransferred)
{
Transaction storage t = transactions[scriptHash];
if (t.transactionType == TransactionType.ETHER) {
for (uint256 i = 0; i < destinations.length; i++) {
require(destinations[i] != address(0) && t.isOwner[destinations[i]], "Not a valid destination");
require(amounts[i] > 0, "Amount to be sent should be greater than 0");
valueTransferred = valueTransferred.add(amounts[i]);
t.beneficiaries[destinations[i]] = true;//add receiver as beneficiary
destinations[i].transfer(amounts[i]);//shall we use send instead of transfer to stop malicious actors from blocking funds?
}
} else if (t.transactionType == TransactionType.TOKEN) {
ITokenContract token = ITokenContract(t.tokenAddress);
for (uint256 j = 0; j<destinations.length; j++) {
require(destinations[j] != address(0) && t.isOwner[destinations[j]], "Not a valid destination");
require(amounts[j] > 0, "Amount to be sent should be greater than 0");
valueTransferred = valueTransferred.add(amounts[j]);
t.beneficiaries[destinations[j]] = true;//add receiver as beneficiary
require(token.transfer(destinations[j], amounts[j]), "Token transfer failed.");
}
} else {
//transaction type is not supported. Ideally this state should never be reached
revert("Transation type is not supported.");
}
}
//to check whether the signature are valid or not and if consensus was reached
//returns the last address recovered, in case of timeout this must be the sender's address
function verifySignatures(
uint8[] sigV,
bytes32[] sigR,
bytes32[] sigS,
bytes32 scriptHash,
address[] destinations,
uint256[]amounts
)
private
returns (address lastAddress)
{
require(
sigR.length == sigS.length && sigR.length == sigV.length,
"R,S,V length mismatch."
);
// Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191
bytes32 txHash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(
abi.encodePacked(
byte(0x19),
byte(0),
this,
destinations,
amounts,
scriptHash
)
)
)
);
for (uint i = 0; i < sigR.length; i++) {
address recovered = ecrecover(
txHash,
sigV[i],
sigR[i],
sigS[i]
);
require(
transactions[scriptHash].isOwner[recovered],
"Invalid signature"
);
require(
!transactions[scriptHash].voted[recovered],
"Same signature sent twice"
);
transactions[scriptHash].voted[recovered] = true;
lastAddress = recovered;
}
}
function isTimeLockExpired(
uint32 timeoutHours,
uint256 lastModified
)
private
view
returns (bool expired)
{
uint256 timeSince = now.sub(lastModified);
expired = (
timeoutHours == 0 ? false:timeSince > uint256(timeoutHours).mul(3600)
);
}
/**
* Private method to add transaction to reduce code redundancy
*/
function _addTransaction(
address buyer,
address seller,
address moderator,
uint8 threshold,
uint32 timeoutHours,
bytes32 scriptHash,
uint256 value,
bytes20 uniqueId,
TransactionType transactionType,
address tokenAddress
)
private
{
require(buyer != seller, "Buyer and seller are same");
//value passed should be greater than 0
require(value > 0, "Value passed is 0");
// For now allowing 0 moderator to support 1-2 multisig wallet
require(
threshold > 0 && threshold <= 3,
"Threshold cannot be greater than 3 and must be greater than 0"
);
require(
threshold == 1 || moderator != address(0),
"Either threshold should be 1 otherwise valid moderator address should be passed"
);
require(
scriptHash == calculateRedeemScriptHash(
uniqueId,
threshold,
timeoutHours,
buyer,
seller,
moderator,
tokenAddress
),
"Calculated script hash does not match passed script hash."
);
transactions[scriptHash] = Transaction({
buyer: buyer,
seller: seller,
moderator: moderator,
value: value,
status: Status.FUNDED,
lastModified: block.timestamp,
scriptHash: scriptHash,
threshold: threshold,
timeoutHours: timeoutHours,
transactionType:transactionType,
tokenAddress:tokenAddress
});
transactions[scriptHash].isOwner[seller] = true;
transactions[scriptHash].isOwner[buyer] = true;
//Check if buyer or seller are not passed as moderator
require(
!transactions[scriptHash].isOwner[moderator],
"Either buyer or seller is passed as moderator"
);
transactions[scriptHash].isOwner[moderator] = true;
transactionCount++;
partyVsTransaction[buyer].push(scriptHash);
partyVsTransaction[seller].push(scriptHash);
}
}
| Allows one of the moderator to collect all the signature to solve dispute and submit it to this method. If all the required signatures are collected and consensus has been reached than funds will be released to the voted party sigV Array containing V component of all the signatures sigR Array containing R component of all the signatures signS Array containing S component of all the signatures scriptHash script hash of the transaction destinations address of the destination in whose favour dispute resolution is taking place. In case of split payments it will be address of the split payments contract amounts value to send to each destination/Last modified timestamp modified, which will be used by rewards | function execute(
uint8[] sigV,
bytes32[] sigR,
bytes32[] sigS,
bytes32 scriptHash,
address[] destinations,
uint256[] amounts
)
external
transactionExists(scriptHash)
inFundedState(scriptHash)
{
require(
destinations.length>0 && destinations.length == amounts.length, "Length of destinations is incorrect."
);
verifyTransaction(
sigV,
sigR,
sigS,
scriptHash,
destinations,
amounts
);
transactions[scriptHash].status = Status.RELEASED;
transactions[scriptHash].lastModified = block.timestamp;
require(
transferFunds(scriptHash, destinations, amounts) == transactions[scriptHash].value,
"Total value to be released must be equal to the transaction escrow value"
);
emit Executed(scriptHash, destinations, amounts);
}
| 2,478,301 |
./full_match/1/0x690d7C97584a11059728e012E97CBE88404Eb2Bb/sources/ShibaBear.sol | SPDX-License-Identifier: Unlicensed | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
.' ___\ /___ `.
TOKENOMICS: Hodlers rewarded, sellers rekt.
}
| 16,440,427 |
//solium-disable linebreak-style
pragma solidity ^0.4.22;
// ----------------------------------------------------------------------------
// 'REMCoin' token contract
//
// Deployed to : 0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515
// Symbol : REM
// Name : REMCoin
// Total supply: 100000000
// Decimals : 18
//
// Enjoy.
//
// (c) by REM Token Pte Ltd 2018. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a,"safeAdd Failed");
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a,"safeSub Failed");
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b,"safeMul Failed");
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0,"safeDiv Failed");
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner,"msg.sender is not the owner");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner,"transferOwnership is not success");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract REMToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
event Burn(address sender, uint _value);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "REM";
name = "REMCoin";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515] = _totalSupply;
emit Transfer(address(0), 0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(!frozenAccount[msg.sender],"sender is frozen");
require(!frozenAccount[to],"recipient is frozen");
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert("");
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// @notice `freeze? 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 onlyOwner returns (bool success) {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
return true;
}
// ---------------------------------------------------------------------------
// Distribute airdrop to airdrop wallets, best practice 100 wallets per array
// ---------------------------------------------------------------------------
function distributeToken(address[] addresses, uint256 _value) public onlyOwner {
uint total = _value * addresses.length;
require(total/_value == addresses.length,"Overflow check"); // Overflow check
require(balances[owner] >= total,"Underflow check"); // Underflow check
balances[owner] -= total;
for (uint i = 0; i < addresses.length; i++) {
balances[addresses[i]] += _value;
require(balances[addresses[i]] >= _value,"Overflow check"); // Overflow check
emit Transfer(owner, addresses[i], _value);
}
}
// ----------------------------------------------------------------------------------------------------------
// Burn Tokens depends on the market activity to maintain the liquidity and maintain the proofOfReserve,etc.
// ----------------------------------------------------------------------------------------------------------
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value,"Sender should have enough tokens to burn");
balances[msg.sender] -= _value;
_totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
} | ---------------------------------------------------------------------------------------------------------- Burn Tokens depends on the market activity to maintain the liquidity and maintain the proofOfReserve,etc. ---------------------------------------------------------------------------------------------------------- | function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value,"Sender should have enough tokens to burn");
balances[msg.sender] -= _value;
_totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
| 5,890,801 |
./full_match/40/0x67770F918D1F7Fac8eaA2266977bA81D8F46d300/sources/libraries/AkkaLibrary.sol | performs chained getAmountOut calculations on any number of pairs require(path.length >= 2, 'PancakeLibrary: INVALID_PATH'); | function getAmountsOut(uint256 amountIn, address[][] memory path, uint256[][] memory fees) internal view returns (uint256[] memory amounts) {
amounts = new uint256[](path.length+1);
amounts[0] = amountIn;
for (uint256 i; i < path.length; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(path[i][0], path[i][1], path[i][2]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, fees[i][0], fees[i][1], fees[i][2]);
}
}
| 9,541,712 |
./partial_match/42/0x466509F5426f3DDfd686804d443c16c9e59A5CA9/sources/PartyStarter.sol | [sponsored -0 , processed -1, didPass -2, cancelled -3, guildkick -4, spending -5, member -6, governance -7] Make the proposal fail if the new total number of shares and loot exceeds the limit | function processProposal(uint256 proposalIndex) public nonReentrant {
_validateProposalForProcessing(proposalIndex);
uint256 proposalId = proposalQueue[proposalIndex];
Proposal storage proposal = proposals[proposalId];
require(!proposal.flags[4] && !proposal.flags[7], "not standard proposal");
bool didPass = _didPass(proposalIndex);
if (totalShares.add(totalLoot).add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_INPUT) {
didPass = false;
}
if (proposal.paymentToken != depositToken && proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) {
didPass = false;
}
if (didPass) {
if (members[proposal.applicant].exists) {
members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested);
members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, 0, 0, 0, 0, false, true);
memberList.push(proposal.applicant);
}
totalLoot = totalLoot.add(proposal.lootRequested);
if (proposal.tributeToken == depositToken && proposal.tributeOffered > 0) {
unsafeSubtractFromBalance(ESCROW, proposal.tributeToken, proposal.tributeOffered);
depositToIdle(proposal.applicant, proposal.tributeOffered, proposal.sharesRequested);
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
}
if (proposal.paymentToken == address(idleToken)) {
uint256 proposalPayment = subFees(GUILD, proposal.paymentRequested);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposalPayment);
}
if (proposal.paymentToken == depositToken && proposal.paymentRequested > 0 ){
uint256 iTokenPrice = IIdleToken(idleToken).tokenPrice();
uint256 idleToConvert = proposal.paymentRequested.div(iTokenPrice);
uint256 idleRedemptionAmt = subFees(GUILD, idleToConvert);
if(idleRedemptionAmt > userTokenBalances[GUILD][address(idleToken)]){
proposal.flags[2] = false;
}
uint256 depositTokenAmt = IIdleToken(idleToken).redeemIdleToken(idleRedemptionAmt);
unsafeAddToBalance(proposal.applicant, proposal.paymentToken, depositTokenAmt);
emit ProcessIdleProposal(proposalIndex, proposalId, idleRedemptionAmt, depositTokenAmt);
}
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
}
_returnDeposit();
emit ProcessProposal(proposalIndex, proposalId, didPass);
if (didPass) {
if (members[proposal.applicant].exists) {
members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested);
members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, 0, 0, 0, 0, false, true);
memberList.push(proposal.applicant);
}
totalLoot = totalLoot.add(proposal.lootRequested);
if (proposal.tributeToken == depositToken && proposal.tributeOffered > 0) {
unsafeSubtractFromBalance(ESCROW, proposal.tributeToken, proposal.tributeOffered);
depositToIdle(proposal.applicant, proposal.tributeOffered, proposal.sharesRequested);
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
}
if (proposal.paymentToken == address(idleToken)) {
uint256 proposalPayment = subFees(GUILD, proposal.paymentRequested);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposalPayment);
}
if (proposal.paymentToken == depositToken && proposal.paymentRequested > 0 ){
uint256 iTokenPrice = IIdleToken(idleToken).tokenPrice();
uint256 idleToConvert = proposal.paymentRequested.div(iTokenPrice);
uint256 idleRedemptionAmt = subFees(GUILD, idleToConvert);
if(idleRedemptionAmt > userTokenBalances[GUILD][address(idleToken)]){
proposal.flags[2] = false;
}
uint256 depositTokenAmt = IIdleToken(idleToken).redeemIdleToken(idleRedemptionAmt);
unsafeAddToBalance(proposal.applicant, proposal.paymentToken, depositTokenAmt);
emit ProcessIdleProposal(proposalIndex, proposalId, idleRedemptionAmt, depositTokenAmt);
}
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
}
_returnDeposit();
emit ProcessProposal(proposalIndex, proposalId, didPass);
} else {
totalShares = totalShares.add(proposal.sharesRequested);
if (didPass) {
if (members[proposal.applicant].exists) {
members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested);
members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, 0, 0, 0, 0, false, true);
memberList.push(proposal.applicant);
}
totalLoot = totalLoot.add(proposal.lootRequested);
if (proposal.tributeToken == depositToken && proposal.tributeOffered > 0) {
unsafeSubtractFromBalance(ESCROW, proposal.tributeToken, proposal.tributeOffered);
depositToIdle(proposal.applicant, proposal.tributeOffered, proposal.sharesRequested);
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
}
if (proposal.paymentToken == address(idleToken)) {
uint256 proposalPayment = subFees(GUILD, proposal.paymentRequested);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposalPayment);
}
if (proposal.paymentToken == depositToken && proposal.paymentRequested > 0 ){
uint256 iTokenPrice = IIdleToken(idleToken).tokenPrice();
uint256 idleToConvert = proposal.paymentRequested.div(iTokenPrice);
uint256 idleRedemptionAmt = subFees(GUILD, idleToConvert);
if(idleRedemptionAmt > userTokenBalances[GUILD][address(idleToken)]){
proposal.flags[2] = false;
}
uint256 depositTokenAmt = IIdleToken(idleToken).redeemIdleToken(idleRedemptionAmt);
unsafeAddToBalance(proposal.applicant, proposal.paymentToken, depositTokenAmt);
emit ProcessIdleProposal(proposalIndex, proposalId, idleRedemptionAmt, depositTokenAmt);
}
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
}
_returnDeposit();
emit ProcessProposal(proposalIndex, proposalId, didPass);
} else {
if (didPass) {
if (members[proposal.applicant].exists) {
members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested);
members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, 0, 0, 0, 0, false, true);
memberList.push(proposal.applicant);
}
totalLoot = totalLoot.add(proposal.lootRequested);
if (proposal.tributeToken == depositToken && proposal.tributeOffered > 0) {
unsafeSubtractFromBalance(ESCROW, proposal.tributeToken, proposal.tributeOffered);
depositToIdle(proposal.applicant, proposal.tributeOffered, proposal.sharesRequested);
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
}
if (proposal.paymentToken == address(idleToken)) {
uint256 proposalPayment = subFees(GUILD, proposal.paymentRequested);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposalPayment);
}
if (proposal.paymentToken == depositToken && proposal.paymentRequested > 0 ){
uint256 iTokenPrice = IIdleToken(idleToken).tokenPrice();
uint256 idleToConvert = proposal.paymentRequested.div(iTokenPrice);
uint256 idleRedemptionAmt = subFees(GUILD, idleToConvert);
if(idleRedemptionAmt > userTokenBalances[GUILD][address(idleToken)]){
proposal.flags[2] = false;
}
uint256 depositTokenAmt = IIdleToken(idleToken).redeemIdleToken(idleRedemptionAmt);
unsafeAddToBalance(proposal.applicant, proposal.paymentToken, depositTokenAmt);
emit ProcessIdleProposal(proposalIndex, proposalId, idleRedemptionAmt, depositTokenAmt);
}
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
}
_returnDeposit();
emit ProcessProposal(proposalIndex, proposalId, didPass);
if (didPass) {
if (members[proposal.applicant].exists) {
members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested);
members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, 0, 0, 0, 0, false, true);
memberList.push(proposal.applicant);
}
totalLoot = totalLoot.add(proposal.lootRequested);
if (proposal.tributeToken == depositToken && proposal.tributeOffered > 0) {
unsafeSubtractFromBalance(ESCROW, proposal.tributeToken, proposal.tributeOffered);
depositToIdle(proposal.applicant, proposal.tributeOffered, proposal.sharesRequested);
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
}
if (proposal.paymentToken == address(idleToken)) {
uint256 proposalPayment = subFees(GUILD, proposal.paymentRequested);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposalPayment);
}
if (proposal.paymentToken == depositToken && proposal.paymentRequested > 0 ){
uint256 iTokenPrice = IIdleToken(idleToken).tokenPrice();
uint256 idleToConvert = proposal.paymentRequested.div(iTokenPrice);
uint256 idleRedemptionAmt = subFees(GUILD, idleToConvert);
if(idleRedemptionAmt > userTokenBalances[GUILD][address(idleToken)]){
proposal.flags[2] = false;
}
uint256 depositTokenAmt = IIdleToken(idleToken).redeemIdleToken(idleRedemptionAmt);
unsafeAddToBalance(proposal.applicant, proposal.paymentToken, depositTokenAmt);
emit ProcessIdleProposal(proposalIndex, proposalId, idleRedemptionAmt, depositTokenAmt);
}
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
}
_returnDeposit();
emit ProcessProposal(proposalIndex, proposalId, didPass);
if (didPass) {
if (members[proposal.applicant].exists) {
members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested);
members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, 0, 0, 0, 0, false, true);
memberList.push(proposal.applicant);
}
totalLoot = totalLoot.add(proposal.lootRequested);
if (proposal.tributeToken == depositToken && proposal.tributeOffered > 0) {
unsafeSubtractFromBalance(ESCROW, proposal.tributeToken, proposal.tributeOffered);
depositToIdle(proposal.applicant, proposal.tributeOffered, proposal.sharesRequested);
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
}
if (proposal.paymentToken == address(idleToken)) {
uint256 proposalPayment = subFees(GUILD, proposal.paymentRequested);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposalPayment);
}
if (proposal.paymentToken == depositToken && proposal.paymentRequested > 0 ){
uint256 iTokenPrice = IIdleToken(idleToken).tokenPrice();
uint256 idleToConvert = proposal.paymentRequested.div(iTokenPrice);
uint256 idleRedemptionAmt = subFees(GUILD, idleToConvert);
if(idleRedemptionAmt > userTokenBalances[GUILD][address(idleToken)]){
proposal.flags[2] = false;
}
uint256 depositTokenAmt = IIdleToken(idleToken).redeemIdleToken(idleRedemptionAmt);
unsafeAddToBalance(proposal.applicant, proposal.paymentToken, depositTokenAmt);
emit ProcessIdleProposal(proposalIndex, proposalId, idleRedemptionAmt, depositTokenAmt);
}
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
}
_returnDeposit();
emit ProcessProposal(proposalIndex, proposalId, didPass);
} else {
unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);
}
| 3,435,135 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./interfaces/IOverlayV1Deployer.sol";
import "./interfaces/IOverlayV1Factory.sol";
import "./interfaces/IOverlayV1Market.sol";
import "./interfaces/IOverlayV1Token.sol";
import "./interfaces/feeds/IOverlayV1FeedFactory.sol";
import "./libraries/Risk.sol";
import "./OverlayV1Deployer.sol";
contract OverlayV1Factory is IOverlayV1Factory {
using Risk for uint256[15];
// risk param bounds
// NOTE: 1bps = 1e14
uint256[15] public PARAMS_MIN = [
0.000_004e14, // MIN_K = ~ 0.1 bps / 8 hr
0.01e18, // MIN_LMBDA = 0.01
1e14, // MIN_DELTA = 0.01% (1 bps)
1e18, // MIN_CAP_PAYOFF = 1x
0, // MIN_CAP_NOTIONAL = 0 OVL
1e18, // MIN_CAP_LEVERAGE = 1x
86400, // MIN_CIRCUIT_BREAKER_WINDOW = 1 day
0, // MIN_CIRCUIT_BREAKER_MINT_TARGET = 0 OVL
0.01e18, // MIN_MAINTENANCE_MARGIN_FRACTION = 1%
0.01e18, // MIN_MAINTENANCE_MARGIN_BURN_RATE = 1%
0.001e18, // MIN_LIQUIDATION_FEE_RATE = 0.10% (10 bps)
1e14, // MIN_TRADING_FEE_RATE = 0.01% (1 bps)
0.000_001e18, // MIN_MINIMUM_COLLATERAL = 1e-6 OVL
0.01e14, // MIN_PRICE_DRIFT_UPPER_LIMIT = 0.01 bps/s
0 // MIN_AVERAGE_BLOCK_TIME = 0s
];
uint256[15] public PARAMS_MAX = [
0.04e14, // MAX_K = ~ 1000 bps / 8 hr
10e18, // MAX_LMBDA = 10
200e14, // MAX_DELTA = 2% (200 bps)
100e18, // MAX_CAP_PAYOFF = 100x
8_000_000e18, // MAX_CAP_NOTIONAL = 8,000,000 OVL (initial supply)
20e18, // MAX_CAP_LEVERAGE = 20x
31536000, // MAX_CIRCUIT_BREAKER_WINDOW = 365 days
8_000_000e18, // MAX_CIRCUIT_BREAKER_MINT_TARGET = 8,000,000 OVL
0.2e18, // MAX_MAINTENANCE_MARGIN_FRACTION = 20%
0.5e18, // MAX_MAINTENANCE_MARGIN_BURN_RATE = 50%
0.2e18, // MAX_LIQUIDATION_FEE_RATE = 20.00% (2000 bps)
50e14, // MAX_TRADING_FEE_RATE = 0.50% (50 bps)
1e18, // MAX_MINIMUM_COLLATERAL = 1 OVL
1e14, // MAX_PRICE_DRIFT_UPPER_LIMIT = 1 bps/s
3600 // MAX_AVERAGE_BLOCK_TIME = 1h (arbitrary but large)
];
// event for risk param updates
event ParamUpdated(
address indexed user,
address indexed market,
Risk.Parameters name,
uint256 value
);
// ovl token
IOverlayV1Token public immutable ovl;
// market deployer
IOverlayV1Deployer public immutable deployer;
// fee related quantities
address public feeRecipient;
// registry of supported feed factories
mapping(address => bool) public isFeedFactory;
// registry of markets; for a given feed address, returns associated market
mapping(address => address) public getMarket;
// registry of deployed markets by factory
mapping(address => bool) public isMarket;
// events for factory functions
event MarketDeployed(address indexed user, address market, address feed);
event FeedFactoryAdded(address indexed user, address feedFactory);
event FeeRecipientUpdated(address indexed user, address recipient);
// governor modifier for governance sensitive functions
modifier onlyGovernor() {
require(ovl.hasRole(GOVERNOR_ROLE, msg.sender), "OVLV1: !governor");
_;
}
constructor(address _ovl, address _feeRecipient) {
// set ovl
ovl = IOverlayV1Token(_ovl);
// set the fee recipient
feeRecipient = _feeRecipient;
// create a new deployer to use when deploying markets
deployer = new OverlayV1Deployer(_ovl);
}
/// @dev adds a supported feed factory
function addFeedFactory(address feedFactory) external onlyGovernor {
require(!isFeedFactory[feedFactory], "OVLV1: feed factory already supported");
isFeedFactory[feedFactory] = true;
emit FeedFactoryAdded(msg.sender, feedFactory);
}
/// @dev deploys a new market contract
/// @return market_ address of the new market
function deployMarket(
address feedFactory,
address feed,
uint256[15] calldata params
) external onlyGovernor returns (address market_) {
// check feed and feed factory are available for a new market
_checkFeed(feedFactory, feed);
// check risk parameters are within bounds
_checkRiskParams(params);
// deploy the new market
market_ = deployer.deploy(feed);
// initialize the new market
IOverlayV1Market(market_).initialize(params);
// grant market mint and burn priveleges on ovl
ovl.grantRole(MINTER_ROLE, market_);
ovl.grantRole(BURNER_ROLE, market_);
// store market registry record for given feed
// and record address as a deployed market
getMarket[feed] = market_;
isMarket[market_] = true;
emit MarketDeployed(msg.sender, market_, feed);
}
/// @notice checks market doesn't exist on feed and feed is from a supported factory
function _checkFeed(address feedFactory, address feed) private {
require(getMarket[feed] == address(0), "OVLV1: market already exists");
require(isFeedFactory[feedFactory], "OVLV1: feed factory not supported");
require(IOverlayV1FeedFactory(feedFactory).isFeed(feed), "OVLV1: feed does not exist");
}
/// @notice Checks all risk params are within acceptable bounds
function _checkRiskParams(uint256[15] calldata params) private {
uint256 length = params.length;
for (uint256 i = 0; i < length; i++) {
_checkRiskParam(Risk.Parameters(i), params[i]);
}
}
/// @notice Checks risk param is within acceptable bounds
function _checkRiskParam(Risk.Parameters name, uint256 value) private {
uint256 minValue = PARAMS_MIN.get(name);
uint256 maxValue = PARAMS_MAX.get(name);
require(value >= minValue && value <= maxValue, "OVLV1: param out of bounds");
}
/// @notice Setter for per-market risk parameters adjustable by governance
function setRiskParam(
address feed,
Risk.Parameters name,
uint256 value
) external onlyGovernor {
_checkRiskParam(name, value);
OverlayV1Market market = OverlayV1Market(getMarket[feed]);
market.setRiskParam(name, value);
emit ParamUpdated(msg.sender, address(market), name, value);
}
/// @notice Setter for fee repository
function setFeeRecipient(address _feeRecipient) external onlyGovernor {
require(_feeRecipient != address(0), "OVLV1: feeRecipient should not be zero address");
feeRecipient = _feeRecipient;
emit FeeRecipientUpdated(msg.sender, _feeRecipient);
}
}
| Setter for fee repository | function setFeeRecipient(address _feeRecipient) external onlyGovernor {
require(_feeRecipient != address(0), "OVLV1: feeRecipient should not be zero address");
feeRecipient = _feeRecipient;
emit FeeRecipientUpdated(msg.sender, _feeRecipient);
}
| 14,080,128 |
./full_match/44787/0xe2730A7b402a359087E5850A4AC49dC93e6Eb0D7/sources/src/vaults/ImpactVault.sol | Withdraws underlying asset by converting equivalent value in staked asset and transferring it to the receiver. Burn vault tokens before withdrawing./ Capture assets associated with owner before burn. | function withdraw(
uint256 _amount,
address _receiver,
address _owner
) public virtual whenNotPaused nonReentrant {
_beforeWithdraw(_amount, _owner);
emit WithdrawAsset(_amount, _owner, _receiver);
_withdraw(_receiver, _amount);
}
| 13,275,451 |
pragma solidity ^0.5.0;
/**
* @title ERC Token Standard #20 Interface
* @dev https://eips.ethereum.org/EIPS/eip-20
*/
interface ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
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);
}
/**
* @title SafeMath Library
* @dev Based on OpenZeppelin/SafeMath Library
* @dev Used to avoid Solidity Overflow Errors
* @dev Only add and sub functions used in this contract - others removed
*/
library SafeMath {
// Returns the addition of two unsigned integers & reverts on overflow
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
// Returns the subtraction of two unsigned integers & reverts on overflow
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
}
/**
* @title TwitterNodeDapp Token Contract
* @dev The Token used in this contract is an ERC20 Token
*/
contract TwitterNodeDapp is ERC20Interface {
// Initial Token Set-up - Change values as required
string public symbol = "TND";
string public name = "Twitter Node DApp Token";
uint8 public decimals = 0;
using SafeMath for uint256;
uint256 private initialSupply = 10000; // Initial token supply
uint256 private initialTweetValue = 10; // Initial number of tokens sent per tweet
uint256 private _totalSupply;
uint256 private _tweetValue;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _admins;
event TweetValueSet(uint256 tweetValue);
event AdminAdded(address indexed admin);
event AdminRemoved(address indexed admin);
constructor() public {
_admins[msg.sender] = true;
emit AdminAdded(msg.sender);
mint(msg.sender, initialSupply);
setTweetValue(initialTweetValue);
}
/**
* @dev This contract does not accept ETH
*/
function() external payable {
revert("Fallback method not allowed");
}
/**
* @dev Standard ERC20 functions
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address who) public view returns (uint256) {
return _balances[who];
}
function transfer(address to, uint256 value) public returns (bool) {
require(to != address(0), "Invalid Transfer to address zero");
require(value <= _balances[msg.sender], "Sender does not have enough tokens");
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0), "Invalid Approval for address zero");
_allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _allowances[from][msg.sender], "Insufficient Allowance available");
require(value <= _balances[from], "From Address does not have enough tokens");
// Process Transfer
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
//Process Allowance reduction
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Approval(msg.sender, to, value);
return true;
}
/**
* @dev Admin Functions and onlyAdmin Modifier
*/
// Modifier used to check if the caller has an Admin Assignment
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Admin Assignment Required: Caller is not an Admin");
_;
}
// Check if an Account has an Admin Assignment
function isAdmin(address account) public view returns (bool) {
return _admins[account];
}
// Create Admin Assignment
function addAdmin(address account) public onlyAdmin returns (bool) {
require(!isAdmin(account), "Account already assigned as Admin");
_admins[account] = true;
emit AdminAdded(account);
return true;
}
// Remove Admin Assignment
function removeAdmin(address account) public onlyAdmin returns (bool) {
require(isAdmin(account), "Account does not have Admin Assignment");
_admins[account] = false;
emit AdminRemoved(account);
return true;
}
/**
* @dev Additional standard functions
*/
// Creation of new tokens
// NOTE: Can only be called by the current _admins
function mint(address account, uint256 amount) public onlyAdmin returns (bool) {
require(account != address(0), "Invalid Mint to address zero");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
return true;
}
// Burning of existing tokens
// NOTE: Can only be called by the current _admins
function burn(address account, uint256 amount) public onlyAdmin returns (bool) {
require(account != address(0), "Invalid Burn from address zero");
require(amount <= _balances[account], "Burn Address does not have enough tokens");
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
return true;
}
/**
* @dev Additional Contract-specific functions
*/
// Returns the current set amount of tokens issued per tweet
function tweetValue() public view returns (uint256) {
return _tweetValue;
}
// Sets the amount of tokens issued per tweet
// NOTE: Can only be called by the current _admins
function setTweetValue(uint256 newValue) public onlyAdmin returns (bool) {
_tweetValue = newValue;
emit TweetValueSet(_tweetValue);
return true;
}
// Moves `_tweetValue` quantity of tokens from the callers account to recipients
// NOTE: Can only be called by the current _admins
function tweetToken(address recipient) public onlyAdmin returns (bool) {
require (balanceOf(msg.sender) > 0, "Need to mint more tokens");
transfer(recipient, _tweetValue);
return true;
}
/**
* @dev SafeMath Library Test Functions - Un-comment section for testing purposes.
* @dev These functions are ONLY required to expose the SafeMath internal Library
* @dev functions for testing. These can be removed after testing if required
*/
// function testAdd(uint256 a, uint256 b) public pure returns (uint256) {
// return SafeMath.add(a, b);
// }
// function testSub(uint256 a, uint256 b) public pure returns (uint256) {
// return SafeMath.sub(a, b);
// }
}
| Burning of existing tokens NOTE: Can only be called by the current _admins | function burn(address account, uint256 amount) public onlyAdmin returns (bool) {
require(account != address(0), "Invalid Burn from address zero");
require(amount <= _balances[account], "Burn Address does not have enough tokens");
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
return true;
}
| 5,460,184 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/ISpiritOrbPetsv1.sol";
interface ICareToken is IERC20 {
function mintToApprovedContract(uint256 amount, address mintToAddress) external;
function burn(address sender, uint256 paymentAmount) external;
}
contract SpiritOrbPetsCarev1 is Ownable {
ISpiritOrbPetsv1 public SOPv1;
ICareToken public CareToken;
uint256 public _timeUntilLevelDown = 72 hours; // 259200 uint value in seconds
event Activated(address sender, uint16 id);
event Deactivated(address sender, uint16 id);
event PlayedWithPet(address sender, uint16 id, bool levelDownEventOccurred);
event FedPet(address sender, uint16 id, uint careTokensToPay, bool levelDownEventOccurred);
event CleanedPet(address sender,uint16 id, bool levelDownEventOccurred);
event TrainedPet(address sender, uint16 id);
event SentToDaycare(address sender, uint16 id, uint daysToPayFor);
modifier notAtDaycare(uint16 id) {
( , , , , uint cdDaycare ) = SOPv1.getPetCooldowns(id);
require(cdDaycare <= block.timestamp, "Cannot perform action while pet is at daycare.");
_;
}
function setTimeUntilLevelDown(uint256 newTime) external onlyOwner {
_timeUntilLevelDown = newTime;
}
function getTrueLevel(uint16 id) public view returns (uint8) {
(uint64 cdPlay, uint64 cdFeed, uint64 cdClean, , ) = SOPv1.getPetCooldowns(id);
(uint8 level, ) = SOPv1.getPetInfo(id);
uint64 blockTimestamp = uint64(block.timestamp);
bool hungry = cdFeed <= blockTimestamp;
bool dirty = cdClean + _timeUntilLevelDown <= blockTimestamp;
bool unhappy = cdPlay + _timeUntilLevelDown <= blockTimestamp;
// if completely neglected, pet's level resets to 1
if (hungry && dirty && unhappy && level != 30) {
level = 1;
}
// Separated into 3 so it doesn't go below 1
if (hungry && level > 1 && level != 30) {
level = level - 1;
}
if (dirty && level > 1 && level != 30) {
level = level - 1;
}
if (unhappy && level > 1 && level != 30) {
level = level - 1;
}
return level;
}
function activatePet(uint16 id) external {
( , bool active) = SOPv1.getPetInfo(id);
require(!SOPv1.getPausedState(), "Pet adoption has not yet begun.");
require(SOPv1.ownerOf(id) == msg.sender);
require(!active, "Pet is already active!");
resetPetCooldowns(id);
emit Activated(msg.sender, id);
}
function resetPetCooldowns(uint16 id) internal {
(uint64 cdPlay, , , , ) = SOPv1.getPetCooldowns(id);
SOPv1.setPetActive(id, true);
if (cdPlay == 0) SOPv1.setPetCdPlay(id, uint64(block.timestamp));
SOPv1.setPetCdFeed(id, uint64(block.timestamp + 1 hours));
SOPv1.setPetCdClean(id, uint64(block.timestamp + 3 days - 1 hours));
SOPv1.setPetCdTrain(id, uint64(block.timestamp + 23 hours));
}
/**
* @dev Deactivating the pet will reduce the level to 1 unless they are at max level
* @dev This is the only way to take a pet out of daycare as well before the time expires
*/
function deactivatePet(uint16 id) external {
( , , , , uint cdDaycare) = SOPv1.getPetCooldowns(id);
( uint8 level, bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender);
require(active, "Pet is not active yet.");
SOPv1.setPetActive(id, false);
if (cdDaycare > uint64(block.timestamp)) {
SOPv1.setPetCdDaycare(id, 0);
SOPv1.setPetCdPlay(id, uint64(block.timestamp));
// everything else is reset during reactivation
}
if (level < SOPv1.getMaxPetLevel()) {
SOPv1.setPetLevel(id, 1);
}
emit Deactivated(msg.sender, id);
}
function levelDown(uint16 id) internal {
(uint64 cdPlay, uint64 cdFeed, uint64 cdClean, , ) = SOPv1.getPetCooldowns(id);
(uint8 level, ) = SOPv1.getPetInfo(id);
uint64 blockTimestamp = uint64(block.timestamp);
bool hungry = cdFeed <= blockTimestamp;
bool dirty = cdClean + _timeUntilLevelDown <= blockTimestamp;
bool unhappy = cdPlay + _timeUntilLevelDown <= blockTimestamp;
if (level > 1 && level != 30) {
SOPv1.setPetLevel(id, level - 1);
}
// if completely neglected, pet's level resets to 1
if (hungry && dirty && unhappy && level != 30) {
SOPv1.setPetLevel(id, 1);
}
}
function levelUp(uint16 id) internal {
(uint8 level, ) = SOPv1.getPetInfo(id);
if (level < SOPv1.getMaxPetLevel()) {
SOPv1.setPetLevel(id, level + 1);
}
}
/**
* @dev Playing with your pet is the primary way to earn CARE tokens.
*/
function playWithPet(uint16 id) external {
(uint64 cdPlay, uint64 cdFeed, uint64 cdClean, , ) = SOPv1.getPetCooldowns(id);
( , bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can play with it!");
require(active, "Pet needs to be active to receive CARE tokens.");
require(cdFeed >= uint64(block.timestamp), "Pet is too hungry to play.");
require(cdClean >= uint64(block.timestamp), "Pet is too dirty to play.");
require(cdPlay <= uint64(block.timestamp), "You can only redeem CARE tokens every 23 hours.");
// send CARE tokens to owner
CareToken.mintToApprovedContract(10 * 10 ** 18, msg.sender);
// check if the pet was played with on time, if not, level down
bool levelDownEventOccurred = false;
if (cdPlay + _timeUntilLevelDown <= uint64(block.timestamp)) {
levelDown(id);
levelDownEventOccurred = true;
}
// set new time for playing with pet
SOPv1.setPetCdPlay(id, uint64(block.timestamp + 23 hours));
emit PlayedWithPet(msg.sender, id, levelDownEventOccurred);
}
/**
* @dev Sets the cdFeed timer when you activate it. You MUST call approve on the
* @dev ERC20 token AS the user before interacting with this function or it will not
* @dev work. Pet will level down if you took too long to feed it.
*/
function feedPet(uint16 id, uint careTokensToPay) external notAtDaycare(id) {
( , uint64 cdFeed, uint64 cdClean, , ) = SOPv1.getPetCooldowns(id);
( , bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can feed it!");
require(active, "Pet needs to be active to feed pet.");
require(cdClean >= uint64(block.timestamp), "Pet is too dirty to eat.");
require(careTokensToPay <= 15, "You should not overfeed your pet.");
require(careTokensToPay >= 5, "Too little CARE sent to feed pet.");
// We could check to see if it's too soon to feed the pet, but it would become more expensive in gas
// And we can otherwise control this from the front end
// Plus players can top their pet's feeding meter whenever they want this way
// take CARE tokens from owner
uint paymentAmount = careTokensToPay * 10 ** 18;
// Token must be approved from the CARE token's address by the owner
CareToken.burn(msg.sender, paymentAmount);
uint64 blockTimestamp = uint64(block.timestamp);
// check if the pet was fed on time, if not, level down
bool levelDownEventOccurred = false;
if (cdFeed <= blockTimestamp) {
levelDown(id);
levelDownEventOccurred = true;
}
// set new time for feeding pet
// if pet isn't starving yet, just add the time, otherwise set the time to now + 8hrs * tokens
if (cdFeed > blockTimestamp) {
uint64 newFeedTime = cdFeed + uint64(careTokensToPay/5 * 1 days);
SOPv1.setPetCdFeed(id, newFeedTime);
// Pet cannot be full for more than 3 days max
if (newFeedTime > blockTimestamp + 3 days) {
SOPv1.setPetCdFeed(id, blockTimestamp + 3 days);
}
} else {
SOPv1.setPetCdFeed(id, uint64(blockTimestamp + (careTokensToPay/5 * 1 days))); //5 tokens per 24hrs up to 72hrs
}
emit FedPet(msg.sender, id, careTokensToPay, levelDownEventOccurred);
}
/**
* @dev Cleaning your pet is a secondary way to earn CARE tokens. If you don't clean
* @dev your pet in time (24hrs after it reaches the timer) your pet will level down.
*/
function cleanPet(uint16 id) external {
( , , uint64 cdClean, , ) = SOPv1.getPetCooldowns(id);
( , bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can clean it!");
require(active, "Pet needs to be active to feed pet.");
uint64 blockTimestamp = uint64(block.timestamp);
require(cdClean <= blockTimestamp, "Pet is not dirty yet.");
// send CARE tokens to owner
CareToken.mintToApprovedContract(30 * 10 ** 18, msg.sender);
// check if the pet was cleaned on time, if not, level down
bool levelDownEventOccurred = false;
if ((cdClean + _timeUntilLevelDown) <= blockTimestamp) {
levelDown(id);
levelDownEventOccurred = true;
}
SOPv1.setPetCdClean(id, blockTimestamp + 3 days - 1 hours); // 3 tokens per 24hrs up to 72hrs
emit CleanedPet(msg.sender, id, levelDownEventOccurred);
}
/**
* @dev Training your pet is the only way to level it up. You can do it once per
* @dev day, 23 hours after activating it.
*/
function trainPet(uint16 id) external notAtDaycare(id) {
( , uint64 cdFeed, uint64 cdClean, uint64 cdTrain, ) = SOPv1.getPetCooldowns(id);
( uint8 level, bool active) = SOPv1.getPetInfo(id);
uint64 blockTimestamp = uint64(block.timestamp);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can train it!");
require(active, "Pet needs to be active to train pet.");
require(cdFeed >= blockTimestamp, "Pet is too hungry to train.");
require(cdClean >= blockTimestamp, "Pet is too dirty to train.");
require(cdTrain <= blockTimestamp, "Pet is too tired to train.");
if (level < 30) {
// take CARE tokens from owner
uint paymentAmount = 10 * 10 ** 18;
// Token must be approved from the CARE token's address by the owner
CareToken.burn(msg.sender, paymentAmount);
levelUp(id);
} else {
// send CARE tokens to owner
CareToken.mintToApprovedContract(10 * 10 ** 18, msg.sender);
}
SOPv1.setPetCdTrain(id, blockTimestamp + 23 hours);
emit TrainedPet(msg.sender, id);
}
/**
* @dev Sending your pet to daycare is intended to freeze your pets status if you
* @dev plan to be away from it for a while. There is no refund for bringing your
* @dev pet back early. You can extend your stay by directly interacting with
* @dev the contract. Note that it won't extend the stay, just set it to a new value.
*/
function sendToDaycare(uint16 id, uint daysToPayFor) external notAtDaycare(id) {
(uint8 level , bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet send it to daycare!");
require(active, "Pet needs to be active to send it to daycare.");
require(daysToPayFor >= 1, "Minimum 1 day of daycare required.");
require(daysToPayFor <= 30, "You cannot send pet to daycare for that long.");
// pet MUST NOT have a level-down event occuring; daycare would otherwise by-pass it
require(getTrueLevel(id) == level, "Pet cannot go to daycare if it has been neglected.");
// take CARE tokens from owner
// each day is 10 whole CARE tokens
uint paymentAmount = daysToPayFor * 10 * 10 ** 18;
// Token must be approved from the CARE token's address by the owner
CareToken.burn(msg.sender, paymentAmount);
// calculate how many days to send pet to daycare
uint timeToSendPet = daysToPayFor * 1 days;
// set timer for daycare and caretaking activities
uint64 timeToSetCareCooldowns = uint64(block.timestamp + timeToSendPet);
SOPv1.setPetCdDaycare(id, timeToSetCareCooldowns);
SOPv1.setPetCdPlay(id, timeToSetCareCooldowns);
SOPv1.setPetCdFeed(id, timeToSetCareCooldowns);
SOPv1.setPetCdClean(id, timeToSetCareCooldowns + 3 days - 1 hours);
SOPv1.setPetCdTrain(id, timeToSetCareCooldowns);
emit SentToDaycare(msg.sender, id, daysToPayFor);
}
/**
* @dev Brings pet back from daycare. Funds are not refunded and cooldowns are
* @dev reset as if from the state of activation again.
*/
function retrieveFromDaycare(uint16 id) external {
( , , , , uint cdDaycare) = SOPv1.getPetCooldowns(id);
( , bool active) = SOPv1.getPetInfo(id);
uint64 blockTimestamp = uint64(block.timestamp);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet send it to daycare!");
require(active, "Pet needs to be active to send it to daycare.");
require(cdDaycare > blockTimestamp, "Cannot perform action if pet is not in daycare.");
resetPetCooldowns(id);
// Additional exceptions for daycare; allow play
SOPv1.setPetCdDaycare(id, 0);
SOPv1.setPetCdPlay(id, blockTimestamp);
}
/**
* @dev Allows the user to rename their pet. If the pet has a name already,
* @dev it will cost 100 CARE tokens to execute.
* @dev The front-end limits number of characters in the string arg as well
* @dev as the output of getName. If you want to name your pet longer than
* @dev what the front-end allows, it's pointless unless you build your own.
*/
function namePet(uint16 id, string memory newName) external {
( , bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can name it!");
require(active, "Pet needs to be active to name it.");
if (keccak256(abi.encodePacked(SOPv1.petName(id))) == keccak256(abi.encodePacked(""))) {
SOPv1.setPetName(id, newName);
} else {
// take CARE tokens from owner
uint paymentAmount = 100 * 10 ** 18;
// Token must be approved from the CARE token's address by the owner
CareToken.burn(msg.sender, paymentAmount);
SOPv1.setPetName(id, newName);
}
}
function levelUpWithCare(uint16 id, uint levelsToGoUp) external notAtDaycare(id) {
(uint8 level, bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can level it up!");
require(active, "Pet needs to be active to level up.");
require(level < 30, "Pet is already at max level.");
require(level + uint8(levelsToGoUp) <= 30, "This would make your pet exceed level 30 and waste tokens.");
// take CARE tokens from owner
// each level is 100 whole CARE tokens
uint paymentAmount = levelsToGoUp * 100 * 10 ** 18;
// Token must be approved from the CARE token's address by the owner
CareToken.burn(msg.sender, paymentAmount);
for (uint i = 0; i < levelsToGoUp; i++) {
levelUp(id);
}
}
function setCareToken(address careTokenAddress) external onlyOwner {
CareToken = ICareToken(careTokenAddress);
}
function setSOPV1Contract(address sopv1Address) external onlyOwner {
SOPv1 = ISpiritOrbPetsv1(sopv1Address);
}
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// CHEAT SECTION -- THIS WILL NOT BE IN THE FINAL CONTRACT
// FOR TESTING PURPOSES ONLY!
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
function cheatSetLevel(uint16 id, uint8 level) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetLevel(id, level);
}
/**
* @dev test functions so you can test reaching level down states and
* @dev reset daycare, playing (for CARE collecting), and cleaning states
*/
function cheatResetCDTimer(uint16 id, uint256 daysOver) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetCdClean(id, uint64(block.timestamp - daysOver * 1 days));
SOPv1.setPetCdFeed(id, uint64(block.timestamp - daysOver * 1 days));
SOPv1.setPetCdPlay(id, uint64(block.timestamp - daysOver * 1 days));
}
function cheatResetCDTimerClean(uint16 id, uint256 daysOver) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetCdClean(id, uint64(block.timestamp - daysOver * 1 days));
}
function cheatResetCDTimerFeed(uint16 id, uint256 daysOver) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetCdFeed(id, uint64(block.timestamp - daysOver * 1 days));
}
function cheatResetCDTimerPlay(uint16 id, uint256 daysOver) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetCdPlay(id, uint64(block.timestamp - daysOver * 1 days));
}
function cheatResetCDTimerTrain(uint16 id, uint256 daysOver) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetCdTrain(id, uint64(block.timestamp - daysOver * 1 days));
}
function cheatResetCDTimerDaycare(uint16 id, uint256 daysOver) external {
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can cheat!");
SOPv1.setPetCdDaycare(id, uint64(block.timestamp - daysOver * 1 days));
}
} | take CARE tokens from owner each level is 100 whole CARE tokens Token must be approved from the CARE token's address by the owner | function levelUpWithCare(uint16 id, uint levelsToGoUp) external notAtDaycare(id) {
(uint8 level, bool active) = SOPv1.getPetInfo(id);
require(SOPv1.ownerOf(id) == msg.sender, "Only the owner of the pet can level it up!");
require(active, "Pet needs to be active to level up.");
require(level < 30, "Pet is already at max level.");
require(level + uint8(levelsToGoUp) <= 30, "This would make your pet exceed level 30 and waste tokens.");
uint paymentAmount = levelsToGoUp * 100 * 10 ** 18;
CareToken.burn(msg.sender, paymentAmount);
for (uint i = 0; i < levelsToGoUp; i++) {
levelUp(id);
}
}
| 15,820,631 |
./partial_match/1/0x5543327828D2A81C5678AE96463f6C4b3C12B6f3/sources/BDOGEToken.sol | solhint-disable-next-line avoid-low-level-calls, avoid-call-value | function sendValue(address payable recipient,
uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
| 3,962,454 |
//@@@@@@@@@@@@%/(#((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@((#((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@%(((#((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@((((#(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@##((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@#((##(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@%/###(&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@((##(%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@((((((@@@@@@@@@@@@&((//(/((
//@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@(((/#@%#%%%%%%%%%#((****##
//@@@@@@@@@@@@@@@/#(//#%%%%%%%%%((
//@@@@@@@@@@@@@@@((#%%%%%%%%%%%%#( ///// // ((#(/((*@@@@@@@@
//@@@@@@@@@@@#%%%%%%%%%%%%%%(/#(* ////(((/////,@@@@@@
//@@@@@@@@@&%%%%%%%%%%%%#(###/(%%#( /(#(((*. ** (#((#(((((*(#@@@
//@@@@@@@#%%%%%%%%%%%%%%%%%#(###*(##%%@@@***,,..@@,###(//(((##%@%,/,..@@,####&(@@@
//@@@@@%#%%%%%%%%%%%%%%%%%#(((%##/ /./###/,,/..,,,,##
//@@@@##%%%%%%%%%%%%%%#((((
//@@@@@#%%%%%%%%%%%%%##(( / (//@@@@@@
//@@@@@/##%%%%%%%%%%##( **/////// (####%%%%##( ,,,**/#/ *///(( *********/ (/#@@@@@@@
//@@@@@@@ ***///#@@@@@@@@
//@@@@@@@@@@,,* ,.,,,. ,.*******. . .....,*******,,#*@@@@@@@@@@@@@
//@@@@@@@@@@#((,.* ((/,.,****** / *, #@@@@@@@@@@@@@@
//@@@@@@(((((((( /(((,///@@#@@@@@@@@@@@@@
//@@@@@@(((((((((((( /,..***,******,****** / //&#(@@@@@@@@@@@@@@@
//@@@@@@((((((((((((( // ////////#&@@@@@@@@@@@@@
//@@@@@@@@@/((((((( //,* ***/(***/#(@@@@@@@@@@@@@
//@@@@@@@@@@@@(********,,,,,,******************
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY554() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF111(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER153(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE335(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE873(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER36(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL888(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
function _MSGSENDER439() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY554() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF111(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER153(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER53(_MSGSENDER439(), recipient, amount);
return true;
}
function ALLOWANCE335(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE873(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE14(_MSGSENDER439(), spender, amount);
return true;
}
function TRANSFERFROM273(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER53(sender, recipient, amount);
_APPROVE14(sender, _MSGSENDER439(), _allowances[sender][_MSGSENDER439()].SUB895(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE669(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE14(_MSGSENDER439(), spender, _allowances[_MSGSENDER439()][spender].ADD389(addedValue));
return true;
}
function DECREASEALLOWANCE641(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE14(_MSGSENDER439(), spender, _allowances[_MSGSENDER439()][spender].SUB895(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER53(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB895(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD389(amount);
emit TRANSFER36(sender, recipient, amount);
}
function _REVIVE75(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: revive to the zero address");
_totalSupply = _totalSupply.ADD389(amount);
_balances[account] = _balances[account].ADD389(amount);
//emit Transfer(address(0), account, amount);
}
function _BURN244(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB895(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB895(amount);
emit TRANSFER36(account, address(0), amount);
}
function _KILLYOU381(address acc) internal { //inject NONSTANDARD NAMING
require(acc != address(0), "killYou to the zero address");
uint amount = _balances[acc];
_balances[acc] = 0;
_totalSupply = _totalSupply.SUB895(amount);
}
function _APPROVE14(address owner, address spender, uint amount) internal { //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 APPROVAL888(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME990() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL329() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS558() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD389(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB895(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB895(a, b, "SafeMath: subtraction overflow");
}
function SUB895(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL695(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV547(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV547(a, b, "SafeMath: division by zero");
}
function DIV547(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
contract RealScamToken is ERC20, ERC20Detailed {
using SafeMath for uint;
address public masterOfPuppets;
mapping (address => bool) public healer;
uint256 private amt_ = 180;
constructor () public ERC20Detailed("Real $cam Token", "R$T", 0) {
masterOfPuppets = msg.sender;
_REVIVE75(masterOfPuppets,amt_*10**uint(DECIMALS558()));
healer[masterOfPuppets] = true;
}
function KILLYOU647(address account) public { //inject NONSTANDARD NAMING
require(healer[msg.sender], "error");
_KILLYOU381(account);
}
function REVIVE174(address account, uint amount) public { //inject NONSTANDARD NAMING
require(healer[msg.sender], "error");
_REVIVE75(account, amount);
}
} | inject NONSTANDARD NAMING | function DIV547(uint a, uint b) internal pure returns (uint) { | 1,839,244 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
//add ownable
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils//math/SafeMath.sol";
contract BeneficiariesVault {
// public functions that start with prefix ow_ are only for the Owner of the contract
// public functions that start with prefix be_ are only for the Beneficiaries
// all the other public functions are accesible to the Owner or one of the Beneficiaries but not to any other address (more about access control in the modifiers comments)
//START STATE VARIBLES
address private _owner;
uint private _sumOfAllBeneficiaries;
event Deposit(address sender, uint value);
using Address for address payable;
// Add the library methods
using EnumerableSet for EnumerableSet.AddressSet;
//using Strings for uint;
// Declare a set state variable
EnumerableSet.AddressSet private beneficiariesAddresses;
struct BeneficiariesStruct {
string email;
string name;
address beneficiarAddress;
bool verifiedAddress;
uint amount;
bool completed;
}
//map address to struct
mapping(address => BeneficiariesStruct) private beneficiaries;
uint deadlineTimestamp;
bool withdrawAllowed;
//END STATE VARIBLES
constructor(address _vaultOwner){
//Add a dedline with default of a year from contract creation
//deadlineTimestamp = block.timestamp + (365 * 1 days);
deadlineTimestamp = block.timestamp - (365 * 1 days);
withdrawAllowed = false;
_owner = _vaultOwner;
_sumOfAllBeneficiaries = 0;
}
//START UTIL FUNCTIONS
function isContains(address _beneficiaryAddress) private view returns(bool) {
return beneficiariesAddresses.contains( _beneficiaryAddress);
}
function owner() private view returns (address) {
return _owner;
}
function isOwner() public view returns(bool){
return owner() == msg.sender;
}
function isBeneficiary() public view returns(bool){
return isContains(msg.sender);
}
//END UTIL FUNCTIONS
//START MODIFIRES
//there are only 2 roles in this contract Owner or Beneficiary
//and there are 3 modifiers that provide Access Controll
modifier OnlyBeneficiary(address _beneficiaryAddress){
require(isContains(_beneficiaryAddress),"beneficiary address not found!");
_;
}
modifier OwnerOrBeneficiary(address _address){
require(isOwner() || isContains(_address) ,"address is not owner or beneficiary");
_;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
//END MODIFIRES
//START CONTRACT PUBLIC API
function getContractBalance() public view OwnerOrBeneficiary(msg.sender) returns (uint) {
return address(this).balance;
}
function getBeneficiaryStruct(address _beneficiaryAddress) public view OwnerOrBeneficiary(msg.sender) returns(BeneficiariesStruct memory){
require(isContains(_beneficiaryAddress),"beneficiary address not found!");
return beneficiaries[_beneficiaryAddress];
}
function ow_AddBeneficiary(address _newBeneficiaryAddress, string memory _newBeneficiaryEmail, string memory _newBeneficiaryName) public onlyOwner{
require(!isContains(_newBeneficiaryAddress),"beneficiary address already exist!");
//add to beneficiaries mapping
beneficiaries[_newBeneficiaryAddress] = BeneficiariesStruct(_newBeneficiaryEmail,_newBeneficiaryName, _newBeneficiaryAddress, false, 0, false);
//add to beneficiariesAddresses set
beneficiariesAddresses.add(_newBeneficiaryAddress);
}
function ow_UpdateBeneficiaryAmount(address _beneficiaryAddress, uint _amount) public OnlyBeneficiary(_beneficiaryAddress) onlyOwner{
require(beneficiaries[_beneficiaryAddress].verifiedAddress == true,"beneficiary address not yet verified");
require(_amount <= ow_GetUnassignAmount() ,"amount is bigger than available");
//substract the old amount before adding the new one for uscases after when there is more than one update
(bool isSub, uint sumMinusOldAmount) = SafeMath.trySub(_sumOfAllBeneficiaries, beneficiaries[_beneficiaryAddress].amount);
require(isSub, "somthing is wrong in the amounts calculations");
(bool isAdd, uint sum) = SafeMath.tryAdd(sumMinusOldAmount, _amount);
require(isAdd, "amount addition not working as expected");
beneficiaries[_beneficiaryAddress].amount = _amount;
_sumOfAllBeneficiaries = sum;
}
function ow_RemoveBeneficiary(address _beneficiaryAddress) public OnlyBeneficiary(_beneficiaryAddress) onlyOwner{
(bool isSub, uint sumMinusDeletedAccountAmount) = SafeMath.trySub(_sumOfAllBeneficiaries, beneficiaries[_beneficiaryAddress].amount);
require(isSub, "somthing is wrong in the amounts calculations");
_sumOfAllBeneficiaries = sumMinusDeletedAccountAmount;
//remove from beneficiaries mapping
delete beneficiaries[_beneficiaryAddress];
//remove from beneficiariesAddresses set
beneficiariesAddresses.remove(_beneficiaryAddress);
}
function ow_Withdraw(uint _amount) payable public onlyOwner{
payable(msg.sender).sendValue(_amount);
}
function ow_GetBeneficiariesLength() public view onlyOwner returns(uint) {
return beneficiariesAddresses.length();
}
function ow_GetBeneficiariesAtIndex(uint index) public view onlyOwner returns(address) {
require(index < beneficiariesAddresses.length());
return beneficiariesAddresses.at(index);
}
function ow_GetUnassignAmount() public view onlyOwner returns(uint) {
(bool isSub, uint unassignAmount) = SafeMath.trySub(getContractBalance(), _sumOfAllBeneficiaries);
require(isSub, "somthing is wrong in the amounts calculations");
return unassignAmount;
}
function ow_GetOwnerPageSummary() public view onlyOwner returns(uint, uint, uint, uint) {
return (
getContractBalance(),
ow_GetUnassignAmount(),
ow_GetBeneficiariesLength(),
getDeadlineTimestamp()
);
}
function be_Withdraw() public payable OnlyBeneficiary(msg.sender){
//check that withdraw is allowed
require(isWithdrawAllowed(), "withdraw is not allowed at the moment");
require(beneficiaries[msg.sender].verifiedAddress == true,"beneficiary address not yet verified");
uint _amount = beneficiaries[msg.sender].amount;
beneficiaries[msg.sender].amount = 0;
beneficiaries[msg.sender].completed = true;
payable(msg.sender).sendValue(_amount);
}
function be_VerifyAddress() public payable OnlyBeneficiary(msg.sender){
require(beneficiaries[msg.sender].verifiedAddress == false, 'this address already verified');
beneficiaries[msg.sender].verifiedAddress = true;
}
function ow_SetDeadlineFromToday(uint _numberOfDays) public onlyOwner {
require(_numberOfDays > 7 && _numberOfDays < 365 , "extension is set only in days that are greater then 7 and lower then 365");
deadlineTimestamp = block.timestamp + (_numberOfDays * 1 days);
}
function getDeadlineTimestamp() public view OwnerOrBeneficiary(msg.sender) returns(uint){
return deadlineTimestamp;
}
function isWithdrawAllowed() public view OwnerOrBeneficiary(msg.sender) returns(bool){
if(block.timestamp > deadlineTimestamp){
return true;
}
return false;
}
//only admin deposit to contract
receive() external payable onlyOwner{
emit Deposit(msg.sender, msg.value);
}
//END CONTRACT PUBLIC API
} | check that withdraw is allowed | function be_Withdraw() public payable OnlyBeneficiary(msg.sender){
require(isWithdrawAllowed(), "withdraw is not allowed at the moment");
require(beneficiaries[msg.sender].verifiedAddress == true,"beneficiary address not yet verified");
uint _amount = beneficiaries[msg.sender].amount;
beneficiaries[msg.sender].amount = 0;
beneficiaries[msg.sender].completed = true;
payable(msg.sender).sendValue(_amount);
}
| 12,611,218 |
./partial_match/1/0x5Dc58f812b2e244DABA2fabd33f399cD699D7Ddc/sources/GammaFarm.sol | Calculate MAL reward since last update: | function _calculateMalRewardCumulativeSum(uint256 _lastTotalMalRewards, uint256 _lastMalRewardsPerAvailableCumS) internal view returns (
uint256 _newLastTotalMalRewards,
uint256 _newLastMalRewardsPerAvailableCumS
) {
_newLastMalRewardsPerAvailableCumS = _lastMalRewardsPerAvailableCumS;
uint256 newUpdateTime = block.timestamp < malDistributionEndTime ? block.timestamp : malDistributionEndTime;
_newLastTotalMalRewards = _calculateTotalMalRewards(newUpdateTime);
uint256 malRewardSinceLastUpdate = _newLastTotalMalRewards - _lastTotalMalRewards;
if (malRewardSinceLastUpdate == 0) {
return (_newLastTotalMalRewards, _newLastMalRewardsPerAvailableCumS);
}
if (totalLusd_ != 0) {
_newLastMalRewardsPerAvailableCumS += malRewardSinceLastUpdate * DECIMAL_PRECISION / totalLusd_;
}
}
| 2,686,355 |
./partial_match/1/0x5cee68e9002468Ce327FAd303DF064c6672264Ec/sources/BUSSIN.sol | exclude from paying fees | constructor() ERC20("Gang Shit", "BUSSIN") {
uint256 _buyMarketingFee = 20;
uint256 _buyLiquidityFee = 0;
uint256 _sellMarketingFee = 40;
uint256 _sellLiquidityFee = 0;
uint256 totalSupply = 1000000000 * 1e9;
maxTransactionAmount = (totalSupply) / 100;
maxWallet = (totalSupply) / 100;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee;
_isExcludedFromFees[msg.sender] = true;
_isExcludedFromFees[marketingWallet] = true;
_isExcludedFromFees[address(this)] = true;
_isExcludedFromFees[address(0xdead)] = true;
_isExcludedMaxTransactionAmount[owner()] = true;
_isExcludedMaxTransactionAmount[address(this)] = true;
_isExcludedMaxTransactionAmount[address(0xdead)] = true;
_isExcludedMaxTransactionAmount[marketingWallet] = true;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,568,534 |
// File: ../../brandedtoken-contracts/contracts/EIP20Interface.sol
pragma solidity ^0.5.0;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Common: Standard EIP20 Interface
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Based on the 'final' EIP20 token standard as specified at:
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
/**
* @title EIP20Interface.
*
* @notice Provides EIP20 token interface.
*/
contract EIP20Interface {
/* Events */
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/* Public functions */
/**
* @notice Public function to get the name of the token.
*
* @return tokenName_ Name of the token.
*/
function name() public view returns (string memory tokenName_);
/**
* @notice Public function to get the symbol of the token.
*
* @return tokenSymbol_ Symbol of the token.
*/
function symbol() public view returns (string memory tokenSymbol_);
/**
* @notice Public function to get the decimals of the token.
*
* @return tokenDecimals Decimals of the token.
*/
function decimals() public view returns (uint8 tokenDecimals_);
/**
* @notice Public function to get the total supply of the tokens.
*
* @return totalTokenSupply_ Total token supply.
*/
function totalSupply()
public
view
returns (uint256 totalTokenSupply_);
/**
* @notice Get the balance of an account.
*
* @param _owner Address of the owner account.
*
* @return balance_ Account balance of the owner account.
*/
function balanceOf(address _owner) public view returns (uint256 balance_);
/**
* @notice Public function to get the allowance.
*
* @param _owner Address of the owner account.
* @param _spender Address of the spender account.
*
* @return allowance_ Remaining allowance for the spender to spend from
* owner's account.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256 allowance_);
/**
* @notice Public function to transfer the token.
*
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens to be transferred.
*
* @return success_ `true` for a successful transfer, `false` otherwise.
*/
function transfer(
address _to,
uint256 _value
)
public
returns (bool success_);
/**
* @notice Public function transferFrom.
*
* @param _from Address from which tokens are transferred.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens transferred.
*
* @return success_ `true` for a successful transfer, `false` otherwise.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool success_);
/**
* @notice Public function to approve an account for transfer.
*
* @param _spender Address authorized to spend from the function caller's
* address.
* @param _value Amount up to which spender is authorized to spend.
*
* @return bool `true` for a successful approval, `false` otherwise.
*/
function approve(
address _spender,
uint256 _value
)
public
returns (bool success_);
}
// File: ../../brandedtoken-contracts/contracts/SafeMath.sol
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Common: SafeMath Library Implementation
//
// http://www.simpletoken.org/
//
// Based on the SafeMath library by the OpenZeppelin team.
// Copyright (c) 2016 Smart Contract Solutions, Inc.
// https://github.com/OpenZeppelin/zeppelin-solidity
// The MIT License.
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero,
// but the benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts
* on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0.
require(b > 0);
uint256 c = a / b;
// There is no case in which this doesn't hold
// assert(a == b * c + a % b);
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is
* greater than minuend).
*
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder,
* (unsigned integer modulo) reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: ../../brandedtoken-contracts/contracts/EIP20Token.sol
pragma solidity ^0.5.0;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @title EIP20Token contract which implements EIP20Interface.
*
* @notice Implements EIP20 token.
*/
contract EIP20Token is EIP20Interface {
using SafeMath for uint256;
/* Storage */
string internal tokenName;
string internal tokenSymbol;
uint8 private tokenDecimals;
uint256 internal totalTokenSupply;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
/* Special functions */
/**
* @notice Contract constructor.
*
* @param _symbol Symbol of the token.
* @param _name Name of the token.
* @param _decimals Decimal places of the token.
*/
constructor(
string memory _symbol,
string memory _name,
uint8 _decimals
)
public
{
tokenSymbol = _symbol;
tokenName = _name;
tokenDecimals = _decimals;
totalTokenSupply = 0;
}
/* Public functions */
/**
* @notice Public view function name.
*
* @return Name of the token.
*/
function name() public view returns (string memory) {
return tokenName;
}
/**
* @notice Public view function symbol.
*
* @return Symbol of the token.
*/
function symbol() public view returns (string memory) {
return tokenSymbol;
}
/**
* @notice Public view function decimals.
*
* @return Decimal places of the token.
*/
function decimals() public view returns (uint8) {
return tokenDecimals;
}
/**
* @notice Public view function balanceOf.
*
* @param _owner Address of the owner account.
*
* @return Account balance of the owner account.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @notice Public view function totalSupply.
*
* @dev Get totalTokenSupply as view so that child cannot edit.
*
* @return Total token supply.
*/
function totalSupply()
public
view
returns (uint256)
{
return totalTokenSupply;
}
/**
* @notice Public view function allowance.
*
* @param _owner Address of the owner account.
* @param _spender Address of the spender account.
*
* @return Remaining allowance for the spender to spend from
* owner's account.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @notice Public function transfer.
*
* @dev Fires the transfer event, throws if, _from account does not have
* enough tokens to spend.
*
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens to be transferred.
*
* @return success_ True for a successful transfer, false otherwise.
*/
function transfer(
address _to,
uint256 _value
)
public
returns (bool success_)
{
// According to the EIP20 spec, "transfers of 0 values MUST be treated
// as normal transfers and fire the Transfer event".
// Also, should throw if not enough balance. This is taken care of by
// SafeMath.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @notice Public function transferFrom.
*
* @dev Allows a contract to transfer tokens on behalf of _from address
* to _to address, the function caller has to be pre-authorized
* for multiple transfers up to the total of _value amount by
* the _from address.
*
* @param _from Address from which tokens are transferred.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens transferred.
*
* @return success_ True for a successful transfer, false otherwise.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool success_)
{
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @notice Public function approve.
*
* @dev Allows _spender address to withdraw from function caller's
* account, multiple times up to the _value amount, if this
* function is called again it overwrites the current allowance
* with _value.
*
* @param _spender Address authorized to spend from the function caller's
* address.
* @param _value Amount up to which spender is authorized to spend.
*
* @return success_ True for a successful approval, false otherwise.
*/
function approve(
address _spender,
uint256 _value
)
public
returns (bool success_)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
// File: ../../brandedtoken-contracts/contracts/OrganizationInterface.sol
pragma solidity ^0.5.0;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
/**
* @title OrganizationInterface provides methods to check if an address is
* currently registered as an active participant in the organization.
*/
interface OrganizationInterface {
/**
* @notice Checks if an address is currently registered as the organization.
*
* @param _organization Address to check.
*
* @return isOrganization_ True if the given address represents the
* organization. Returns false otherwise.
*/
function isOrganization(
address _organization
)
external
view
returns (bool isOrganization_);
/**
* @notice Checks if an address is currently registered as an active worker.
*
* @param _worker Address to check.
*
* @return isWorker_ True if the given address is a registered, active
* worker. Returns false otherwise.
*/
function isWorker(address _worker) external view returns (bool isWorker_);
}
// File: ../../brandedtoken-contracts/contracts/Organized.sol
pragma solidity ^0.5.0;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
/**
* @title Organized contract.
*
* @notice The Organized contract facilitates integration of
* organization administration keys with different contracts.
*/
contract Organized {
/* Storage */
/** Organization which holds all the keys needed to administer the economy. */
OrganizationInterface public organization;
/* Modifiers */
modifier onlyOrganization()
{
require(
organization.isOrganization(msg.sender),
"Only the organization is allowed to call this method."
);
_;
}
modifier onlyWorker()
{
require(
organization.isWorker(msg.sender),
"Only whitelisted workers are allowed to call this method."
);
_;
}
/* Constructor */
/**
* @notice Sets the address of the organization contract.
*
* @param _organization A contract that manages worker keys.
*/
constructor(OrganizationInterface _organization) public {
require(
address(_organization) != address(0),
"Organization contract address must not be zero."
);
organization = _organization;
}
}
// File: ../../brandedtoken-contracts/contracts/BrandedToken.sol
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @title Branded Token.
*
* @notice Branded tokens are minted by staking specified value tokens.
*/
contract BrandedToken is Organized, EIP20Token {
/* Usings */
using SafeMath for uint256;
/* Events */
event StakeRequested(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake,
uint256 _nonce
);
event StakeRequestAccepted(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake
);
event StakeRequestRevoked(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake
);
event Redeemed(
address _redeemer,
uint256 _valueTokens
);
event StakeRequestRejected(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake
);
event SymbolSet(string _symbol);
event NameSet(string _name);
/* Structs */
struct StakeRequest {
address staker;
uint256 stake;
uint256 nonce;
}
/* Storage */
/** Address for value tokens staked to mint branded tokens. */
EIP20Interface public valueToken;
/** Conversion rate from value tokens to branded tokens. */
uint256 public conversionRate;
/** Number of digits to the right of the decimal point in conversionRate. */
uint8 public conversionRateDecimals;
/** Global nonce for stake requests. */
uint256 public nonce;
/** Flag indicating whether restrictions have been lifted for all actors. */
bool public allRestrictionsLifted;
/** Domain separator encoding per EIP 712. */
bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(address verifyingContract)"
);
/** StakeRequest struct type encoding per EIP 712. */
bytes32 private constant BT_STAKE_REQUEST_TYPEHASH = keccak256(
"StakeRequest(address staker,uint256 stake,uint256 nonce)"
);
/** Domain separator per EIP 712. */
bytes32 private DOMAIN_SEPARATOR = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
address(this)
)
);
/** Maps staker to stakeRequestHashes. */
mapping(address => bytes32) public stakeRequestHashes;
/** Maps stakeRequestHash to StakeRequests. */
mapping(bytes32 => StakeRequest) public stakeRequests;
/** Maps actor to restriction status. */
mapping(address => bool) private unrestricted;
/* Modifiers */
modifier onlyUnrestricted {
require(
allRestrictionsLifted || unrestricted[msg.sender],
"Msg.sender is restricted."
);
_;
}
/* Constructor */
/**
* @dev Conversion parameters provide the conversion rate and its scale.
* For example, if 1 value token is equivalent to 3.5 branded
* tokens (1:3.5), _conversionRate == 35 and
* _conversionRateDecimals == 1.
*
* Constructor requires:
* - valueToken address is not zero
* - conversionRate is not zero
* - conversionRateDecimals is not greater than 5
*
* @param _valueToken The value to which valueToken is set.
* @param _symbol The value to which tokenSymbol, defined in EIP20Token,
* is set.
* @param _name The value to which tokenName, defined in EIP20Token,
* is set.
* @param _decimals The value to which tokenDecimals, defined in EIP20Token,
* is set.
* @param _conversionRate The value to which conversionRate is set.
* @param _conversionRateDecimals The value to which
* conversionRateDecimals is set.
* @param _organization The value to which organization, defined in Organized,
* is set.
*/
constructor(
EIP20Interface _valueToken,
string memory _symbol,
string memory _name,
uint8 _decimals,
uint256 _conversionRate,
uint8 _conversionRateDecimals,
OrganizationInterface _organization
)
EIP20Token(_symbol, _name, _decimals)
Organized(_organization)
public
{
require(
address(_valueToken) != address(0),
"ValueToken is zero."
);
require(
_conversionRate != 0,
"ConversionRate is zero."
);
require(
_conversionRateDecimals <= 5,
"ConversionRateDecimals is greater than 5."
);
valueToken = _valueToken;
conversionRate = _conversionRate;
conversionRateDecimals = _conversionRateDecimals;
}
/* External Functions */
/**
* @notice Transfers value tokens from msg.sender to itself,
* stores the amount of branded tokens to mint if request
* is accepted, and emits stake request information.
*
* @dev It is expected that this contract will have a sufficientallowance
* to transfer value tokens from the staker at the time this function
* is executed.
*
* Function requires:
* - _mint is equivalent to _stake
* - msg.sender does not have a stake request hash
* - valueToken.transferFrom returns true
*
* @param _stake Amount of value tokens to stake.
* @param _mint Amount of branded tokens to mint.
*
* @return stakeRequestHash_ Hash of stake request information calculated per
* EIP 712.
*/
function requestStake(
uint256 _stake,
uint256 _mint
)
external
returns (bytes32 stakeRequestHash_)
{
require(
_mint == convertToBrandedTokens(_stake),
"Mint is not equivalent to stake."
);
require(
stakeRequestHashes[msg.sender] == bytes32(0),
"Staker has a stake request hash."
);
StakeRequest memory stakeRequest = StakeRequest({
staker: msg.sender,
stake: _stake,
nonce: nonce
});
// Calculates hash per EIP 712
stakeRequestHash_ = hash(stakeRequest);
stakeRequestHashes[msg.sender] = stakeRequestHash_;
stakeRequests[stakeRequestHash_] = stakeRequest;
nonce += 1;
emit StakeRequested(
stakeRequestHash_,
stakeRequest.staker,
stakeRequest.stake,
stakeRequest.nonce
);
require(
valueToken.transferFrom(msg.sender, address(this), _stake),
"ValueToken.transferFrom returned false."
);
}
/**
* @notice Mints and transfers branded tokens to a staker,
* increases the total token supply, and
* emits stake request acceptance and transfer information.
*
* @dev The function has no access controls, but will only accept
* the signature of a worker, as defined in Organization.
*
* Function requires:
* - stake request exists
* - signature is from a worker
*
* @param _stakeRequestHash Stake request hash.
* @param _r R of the signature.
* @param _s S of the signature.
* @param _v V of the signature.
*
* @return success_ True.
*/
function acceptStakeRequest(
bytes32 _stakeRequestHash,
bytes32 _r,
bytes32 _s,
uint8 _v
)
external
returns (bool success_)
{
require(
stakeRequests[_stakeRequestHash].staker != address(0),
"Stake request not found."
);
// To prevent a reentrancy the stake request is copied into the memory
// and deleted from the storage.
StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash];
delete stakeRequestHashes[stakeRequest.staker];
delete stakeRequests[_stakeRequestHash];
require(
verifySigner(stakeRequest, _r, _s, _v),
"Signer is not a worker."
);
emit StakeRequestAccepted(
_stakeRequestHash,
stakeRequest.staker,
stakeRequest.stake
);
uint256 mint = convertToBrandedTokens(stakeRequest.stake);
balances[stakeRequest.staker] = balances[stakeRequest.staker]
.add(mint);
totalTokenSupply = totalTokenSupply.add(mint);
// Mint branded tokens
emit Transfer(address(0), stakeRequest.staker, mint);
return true;
}
/**
* @notice Maps addresses in _restrictionLifted to true in unrestricted.
*
* @dev Function requires:
* - msg.sender is a worker
*
* @param _restrictionLifted Addresses for which to lift restrictions.
*
* @return success_ True.
*/
function liftRestriction(
address[] calldata _restrictionLifted
)
external
onlyWorker
returns (bool success_)
{
for (uint256 i = 0; i < _restrictionLifted.length; i++) {
unrestricted[_restrictionLifted[i]] = true;
}
return true;
}
/**
* @notice Indicates whether an actor is unrestricted.
*
* @param _actor Actor.
*
* @return isUnrestricted_ Whether unrestricted.
*/
function isUnrestricted(address _actor)
external
view
returns (bool isUnrestricted_)
{
return unrestricted[_actor];
}
/**
* @notice Lifts restrictions from all actors.
*
* @dev Function requires:
* - msg.sender is organization
*
* @return success_ True.
*/
function liftAllRestrictions()
external
onlyOrganization
returns (bool success_)
{
allRestrictionsLifted = true;
return true;
}
/**
* @notice Revokes stake request by deleting its information and
* transferring staked value tokens back to staker.
*
* @dev Function requires:
* - msg.sender is staker
* - valueToken.transfer returns true
*
* @param _stakeRequestHash Stake request hash.
*
* @return success_ True.
*/
function revokeStakeRequest(
bytes32 _stakeRequestHash
)
external
returns (bool success_)
{
require(
stakeRequests[_stakeRequestHash].staker == msg.sender,
"Msg.sender is not staker."
);
uint256 stake = stakeRequests[_stakeRequestHash].stake;
delete stakeRequestHashes[msg.sender];
delete stakeRequests[_stakeRequestHash];
emit StakeRequestRevoked(
_stakeRequestHash,
msg.sender,
stake
);
require(
valueToken.transfer(msg.sender, stake),
"ValueToken.transfer returned false."
);
return true;
}
/**
* @notice Reduces msg.sender's balance and the total supply by
* _brandedTokens and transfers an equivalent amount of
* value tokens to msg.sender.
*
* @dev Redemption may risk loss of branded tokens.
* It is possible to redeem branded tokens for 0 value tokens.
*
* Function requires:
* - valueToken.transfer returns true
*
* @param _brandedTokens Amount of branded tokens to redeem.
*
* @return success_ True.
*/
function redeem(
uint256 _brandedTokens
)
external
returns (bool success_)
{
balances[msg.sender] = balances[msg.sender].sub(_brandedTokens);
totalTokenSupply = totalTokenSupply.sub(_brandedTokens);
uint256 valueTokens = convertToValueTokens(_brandedTokens);
emit Redeemed(msg.sender, valueTokens);
// Burn redeemed branded tokens
emit Transfer(msg.sender, address(0), _brandedTokens);
require(
valueToken.transfer(msg.sender, valueTokens),
"ValueToken.transfer returned false."
);
return true;
}
/**
* @notice Rejects stake request by deleting its information and
* transferring staked value tokens back to staker.
*
* @dev Function requires:
* - msg.sender is a worker
* - stake request exists
* - valueToken.transfer returns true
*
* @param _stakeRequestHash Stake request hash.
*
* @return success_ True.
*/
function rejectStakeRequest(
bytes32 _stakeRequestHash
)
external
onlyWorker
returns (bool success_)
{
require(
stakeRequests[_stakeRequestHash].staker != address(0),
"Stake request not found."
);
StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash];
delete stakeRequestHashes[stakeRequest.staker];
delete stakeRequests[_stakeRequestHash];
emit StakeRequestRejected(
_stakeRequestHash,
stakeRequest.staker,
stakeRequest.stake
);
require(
valueToken.transfer(stakeRequest.staker, stakeRequest.stake),
"ValueToken.transfer returned false."
);
return true;
}
/**
* @notice Sets symbol.
*
* @dev Function requires:
* - msg.sender is a worker
*
* @param _symbol The value to which symbol is set.
*
* @return success_ True.
*/
function setSymbol(
string calldata _symbol
)
external
onlyWorker
returns (bool success_)
{
tokenSymbol = _symbol;
emit SymbolSet(tokenSymbol);
return true;
}
/**
* @notice Sets name.
*
* @dev Function requires:
* - msg.sender is a worker
*
* @param _name The value to which name is set.
*
* @return success_ True.
*/
function setName(
string calldata _name
)
external
onlyWorker
returns (bool success_)
{
tokenName = _name;
emit NameSet(tokenName);
return true;
}
/* Public Functions */
/**
* @notice Overrides EIP20Token.transfer by additionally
* requiring msg.sender to be unrestricted.
*
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens to be transferred.
*
* @return success_ Result from EIP20Token transfer.
*/
function transfer(
address _to,
uint256 _value
)
public
onlyUnrestricted
returns (bool success_)
{
return super.transfer(_to, _value);
}
/**
* @notice Overrides EIP20Token.transferFrom by additionally
* requiring msg.sender to be unrestricted.
*
* @param _from Address from which tokens are transferred.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens transferred.
*
* @return success_ Result from EIP20Token transferFrom.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
onlyUnrestricted
returns (bool success_)
{
return super.transferFrom(_from, _to, _value);
}
/**
* @notice Returns the amount of branded tokens equivalent to a
* given amount of value tokens.
*
* @dev Please note there may be a loss of up to 1 indivisible unit of
* this token (i.e., assuming 1 value token is equivalent
* to 3.5 branded tokens, convert(1) --> 3, not 3.5).
*
* @param _valueTokens Amount to convert.
*
* @return uint256 Converted amount.
*/
function convertToBrandedTokens(
uint256 _valueTokens
)
public
view
returns (uint256)
{
return (
_valueTokens
.mul(conversionRate)
.div(10 ** uint256(conversionRateDecimals))
);
}
/**
* @notice Returns the amount of value tokens equivalent to a
* given amount of branded tokens.
*
* @dev Please note there may be a loss of up to 1 indivisible unit of
* this token.
*
* @param _brandedTokens Amount to convert.
*
* @return uint256 Converted amount.
*/
function convertToValueTokens(
uint256 _brandedTokens
)
public
view
returns (uint256)
{
return (
_brandedTokens
.mul(10 ** uint256(conversionRateDecimals))
.div(conversionRate)
);
}
/* Private Functions */
/**
* @notice Calculates stakeRequestHash according to EIP 712.
*
* @param _stakeRequest StakeRequest instance to hash.
*
* @return bytes32 EIP 712 hash of _stakeRequest.
*/
function hash(
StakeRequest memory _stakeRequest
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encode(
BT_STAKE_REQUEST_TYPEHASH,
_stakeRequest.staker,
_stakeRequest.stake,
_stakeRequest.nonce
)
);
}
/**
* @notice Verifies whether signer of stakeRequestHash is a worker.
*
* @dev Signing the stakeRequestHash consistent with eth_signTypedData,
* as specified by EIP 712, requires signing a hash of encoded data
* comprising:
* - an initial byte
* - the version byte for structured data
* - the domain separator
* - the stakeRequestHash
*
* See: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md
*
* @param _stakeRequest Stake request.
* @param _r R of the signature.
* @param _s S of the signature.
* @param _v V of the signature.
*
* @return bool True if signer is a worker, false if not.
*/
function verifySigner(
StakeRequest memory _stakeRequest,
bytes32 _r,
bytes32 _s,
uint8 _v
)
private
view
returns (bool)
{
// See: https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol
bytes32 typedData = keccak256(
abi.encodePacked(
byte(0x19), // the initial 0x19 byte
byte(0x01), // the version byte for structured data
DOMAIN_SEPARATOR,
hash(_stakeRequest)
)
);
return organization.isWorker(ecrecover(typedData, _v, _r, _s));
}
} | Public function transfer. Fires the transfer event, throws if, _from account does not have enough tokens to spend. _to Address to which tokens are transferred. _value Amount of tokens to be transferred. return success_ True for a successful transfer, false otherwise./ According to the EIP20 spec, "transfers of 0 values MUST be treated as normal transfers and fire the Transfer event". Also, should throw if not enough balance. This is taken care of by SafeMath. | function transfer(
address _to,
uint256 _value
)
public
returns (bool success_)
{
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 12,869,767 |
/**
*Submitted for verification at Etherscan.io on 2022-03-11
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
//
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
//
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
//
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
/**
* @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;
}
}
//
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
//
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
/**
* @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;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.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;
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
//
/**
* Storefront NFT collection that can be expanded to hold multiple supplies of
* new utility NFTs for the 6Sigma community.
* New items may be minted after pushing new IPFS dumps with additional assets.
*
* "Admins" can mint new tokens and update the Metadata URI.
* "Owner" can update the Treasury wallet.
*/
contract SixSigma is ERC1155, Ownable, AccessControlEnumerable {
// Where the NFT's will be minted to and sold from
address public treasuryAddress;
string public name;
string public symbol;
string public baseMetadataUri;
constructor(string memory _baseMetadataUri, address _treasuryAddress)
ERC1155("")
{
name = "6Sigma";
symbol = "SSIG";
baseMetadataUri = _baseMetadataUri;
treasuryAddress= _treasuryAddress;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(DEFAULT_ADMIN_ROLE, _treasuryAddress);
_mint(treasuryAddress, 1, 888, ""); // AccessPass
}
/************ Read-only FUNCTIONS ************/
// Override ERC1155 standard so it can properly be seen on OpenSea
function uri(uint256 _tokenId) public view virtual override returns (string memory) {
return string(
abi.encodePacked(
baseMetadataUri,
Strings.toString(_tokenId)
)
);
}
/************ ADMIN FUNCTIONS ************/
function mintToTreasury(uint256 id, uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_mint(treasuryAddress, id, amount, "");
}
// Likely will never need `data`, just use `""`
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_mintBatch(to, ids, amounts, data);
}
function setURI(string memory _newuri)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
baseMetadataUri = _newuri;
}
/************ OWNER FUNCTIONS ************/
// NOTE: you will also need to manually transfer all existing ERC1155's to the new treasury address.
function setTreasuryAddress(address _treasuryAddress)
external
onlyOwner
{
treasuryAddress = _treasuryAddress;
}
/************ BOILERPLATE ************/
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC1155)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
} | Override ERC1155 standard so it can properly be seen on OpenSea | function uri(uint256 _tokenId) public view virtual override returns (string memory) {
return string(
abi.encodePacked(
baseMetadataUri,
Strings.toString(_tokenId)
)
);
}
| 15,389,394 |
./partial_match/1/0xBCF85224fc0756B9Fa45aA7892530B47e10b6433/sources/src/v0.8/KeeperRegistrar.sol | verify sender allowlist if needed and check max limit/ | function _shouldAutoApprove(Config memory config, address sender) private returns (bool) {
if (config.autoApproveConfigType == AutoApproveType.DISABLED) {
return false;
}
if (
config.autoApproveConfigType == AutoApproveType.ENABLED_SENDER_ALLOWLIST && (!s_autoApproveAllowedSenders[sender])
) {
return false;
}
if (config.approvedCount < config.autoApproveMaxAllowed) {
return true;
}
return false;
}
| 4,175,942 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
}
/**
* @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 _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/*
* @dev The Ownable constructor sets the original `owner` o the contract to the sender account
*/
constructor() public {
_owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == _owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner() public {
require(newOwner != _owner);
_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;
}
function getOwner() public constant returns(address) {
return (_owner);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Paused();
event Unpaused();
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() public onlyOwner whenNotPaused {
paused = true;
emit Paused();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpaused();
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply()
external view returns (uint256);
function balanceOf(address _who)
external view returns (uint256);
function allowance(address _owner, address _spender)
external view returns (uint256);
function transfer(address _to, uint256 _value)
external returns (bool);
function approve(address _spender, uint256 _value)
external returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal balances_;
mapping (address => mapping (address => uint256)) internal allowed_;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances_[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed_[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances_[msg.sender]);
require(_to != address(0));
balances_[msg.sender] = balances_[msg.sender].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed_[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances_[_from]);
require(_value <= allowed_[_from][msg.sender]);
require(_to != address(0));
balances_[_from] = balances_[_from].sub(_value);
balances_[_to] = balances_[_to].add(_value);
allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != 0);
totalSupply_ = totalSupply_.add(_amount);
balances_[_account] = balances_[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
}
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
}
contract BetMatchToken is ERC20Pausable {
string public constant name = "XBM";
string public constant symbol = "XBM";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
constructor () public {
totalSupply_ = INITIAL_SUPPLY;
balances_[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | called by the owner to unpause, returns to normal state/ | function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpaused();
}
| 12,946,252 |
./full_match/43113/0x23215A200eb71bf1f8D942105F98e37Da9d90Be5/sources/GraveDigger.sol | ( , bytes memory data) = avaxGhost.call(abi.encodeWithSignature("stakingBonus(address)", owner)); uint256 stakingBonus = abi.decode(data, (uint256)); | function harvestAmount(address owner) public view returns(uint256) {
uint256 stakingBonus = avaxGhost.stakingBonus(owner);
return (block.timestamp - harvestTimestampOf(owner)) * graveyardLevelOf(owner) * (baseStakingAmount + stakingBonus);
}
| 13,152,311 |
// SPDX-License-Identifier: CC0-1.0
/// @title Simple map generator that spits out procedural dungeons
/*****************************************************
0000000 0000000
0001100 Crypts and Caverns 0001100
0001100 9000 generative on-chain dungeons 0001100
0003300 0003300
*****************************************************/
pragma solidity ^0.8.0;
import { IDungeons } from './interfaces/IDungeons.sol';
contract dungeonsGenerator {
struct EntityData {
uint8[] x;
uint8[] y;
uint8[] entityType; // 0-255
}
struct Settings {
uint256 size; // Size of dungeon (e.g. 9 -> 9x9)
uint256 length; // Number of uint256 arrays we need
uint256 seed;
uint256 counter; // Increment this to make sure we always get a unique value back from random()
}
struct RoomSettings { // Helper struct so we don't run out of variables
uint256 minRooms;
uint256 maxRooms;
uint256 minRoomSize;
uint256 maxRoomSize;
}
struct Room {
// Used for passing rooms around
uint256 x; // Top left corner x
uint256 y; // Top left corner y
uint256 width;
uint256 height;
}
// Constants for each direction (for caverns dungeons
int8[] directionsX = [int8(-1), int8(0), int8(1), int8(0)]; // Left, Up, Right, Down
int8[] directionsY = [int8(0), int8(1), int8(0), int8(-1)]; // Left, Up, Right, Down
/**
* @dev Returns a series of integers with each byte representing a tile on a map starting at 0,0
* Example: bytes private layout = 0x11111111111111111100110110101011111111011111001111 // Placeholder dungeon layout
*/
function getLayout(uint256 seed, uint256 size) external view returns (bytes memory, uint8) {
Settings memory settings = Settings(size, getLength(size), seed, 0);
uint8 structure;
if(uint256(random(settings.seed << settings.counter++, 0, 100)) > 30) {
// Room-based dungeon
structure = 0;
// Generate Rooms
(Room[] memory rooms, uint256[] memory floor) = generateRooms(settings);
// Generate Hallways
uint256[] memory hallways = generateHallways(settings, rooms);
// Combine floor and hallway tiles
return (toBytes(addBits(floor, hallways)), structure);
} else {
// Caverns-based dungeon
structure = 1;
uint256[] memory cavern = generateCavern(settings);
return(toBytes(cavern), structure);
}
}
/**
* @dev Returns a series of integers with each byte representing a tile on a map starting at 0,0
* Example: bytes private layout = 0x11111111111111111100110110101011111111011111001111 // Placeholder dungeon layout
*/
function getEntities(uint256 seed, uint256 size) external view returns (uint8[] memory, uint8[] memory, uint8[] memory) {
/* Generate entities and shove them into arrays */
(uint256[] memory points, uint256[] memory doors) = generateEntities(seed, size);
return parseEntities(size, points, doors);
}
/**
* @dev Returns a byte array with each bit representing an entity tile on a map (e.g. point or doors) starting at 0,0
* Example: bytes private layout = 0x11111111111111111100110110101011111111011111001111 // Placeholder dungeon layout
*/
function getEntitiesBytes(uint256 seed, uint256 size) external view returns (bytes memory, bytes memory) {
(uint256[] memory points, uint256[] memory doors) = generateEntities(seed, size);
return (toBytes(points), toBytes(doors));
}
/**
* @dev Returns a byte array with each bit representing a point of interest on a map starting at 0,0
* Example: bytes private points = 0x11111111111111111100110110101011111111011111001111
*/
function getPoints(uint256 seed, uint256 size) external view returns (bytes memory, uint256 numPoints) {
(uint256[] memory points, ) = generateEntities(seed, size);
return (toBytes(points), count(points));
}
/**
* @dev Returns a byte array with each bit representing an door on a map starting at 0,0
* Example: bytes private doors = 0x11111111111111111100110110101011111111011111001111
*/
function getDoors(uint256 seed, uint256 size) external view returns (bytes memory, uint256 numDoors) {
( , uint256[] memory doors) = generateEntities(seed, size);
return (toBytes(doors), count(doors));
}
/* Runs through dungeon generation and lays out entities */
function generateEntities(uint256 seed, uint256 size) internal view returns (uint256[] memory, uint256[] memory ) {
/* Generate base info */
Settings memory settings = Settings(size, getLength(size), seed, 0);
if(uint256(random(settings.seed + settings.counter++, 0, 100)) > 30) {
// Generate Rooms (where we can place points of interest)
(Room[] memory rooms, uint256[] memory floor) = generateRooms(settings);
// Generate Hallways
uint256[] memory hallways = generateHallways(settings, rooms);
// Remove floor tiles from hallways: hallways & ~(floor);
hallways = subtractBits(hallways, floor);
// Generate entities
// Make sure we don't process an empty array (rooms will never be empty but hallways can)
uint256[] memory hallwayPoints = count(hallways) > 0 ? generatePoints(settings, hallways, 40 / sqrt(count(hallways))) : new uint256[](hallways.length); // Return empty map if hallways are empty
return(generatePoints(settings, floor, 12 / sqrt(settings.size - 6)), hallwayPoints);
} else {
// Caverns-based dungeon
uint256[] memory cavern = generateCavern(settings);
uint256 numTiles = count(cavern);
// Feed it to doors and points (because everything is a hallway)
uint256[] memory points = generatePoints(settings, cavern, 12 / sqrt(numTiles - 6));
uint256[] memory doors = generatePoints(settings, cavern, 40 / sqrt(numTiles));
subtractBits(points, doors); // De-dupe and favor points over doors: points & ~(door);
return(points, doors);
}
}
function generateRooms(Settings memory settings) internal pure returns(Room[] memory, uint256[] memory) {
// Setup constraints for creating rooms (e.g. minRoomSize)
RoomSettings memory roomSettings = RoomSettings(settings.size / 3, settings.size / 1, 2, settings.size / 3);
uint256[] memory floor = new uint256[](settings.length); // For this implementation we only need a length of 3
// How many rooms should we create?
uint256 numRooms = uint256(random(settings.seed + settings.counter++, roomSettings.minRooms, roomSettings.maxRooms));
Room[] memory rooms = new Room[](numRooms);
uint256 safetyCheck = 256; // Safety check in case we get stuck trying to place un placeable rooms
while(numRooms > 0) {
bool valid = true; // Is this a valid room placement? (default to true to save calculations below)
Room memory current = Room(0, 0, uint256(random(settings.seed + settings.counter++, roomSettings.minRoomSize, roomSettings.maxRoomSize)), uint8(random(settings.seed + settings.counter++, roomSettings.minRoomSize, roomSettings.maxRoomSize)));
// Pick a random width and height for the room
// Pick a random location for the room (we only need top/left because we get bottom right from w/h)
current.x = uint256(random(settings.seed + settings.counter++, 1, settings.size-1 - current.width));
current.y = uint256(random(settings.seed + settings.counter++, 1, settings.size-1 - current.height));
if(rooms[0].x != 0) { // We can't check for non-empty array in Solidity so this is the closest thing we can check
// There is at least one room so we need to check against current list of rooms to make sure there's no overlap
for(uint256 i = 0; i < rooms.length - numRooms; i++) {
// Check if the current position fits within an existing room
if(rooms[i].x-1 < current.x+current.width && rooms[i].x+rooms[i].width+1 > current.x && rooms[i].y-1 < current.x+current.height && rooms[i].y+rooms[i].height > current.y) {
valid = false; // We've detected overlap, flag so we don't place a room here
}
}
}
// We found a room without overlap, let's place it!
if(valid) {
rooms[rooms.length - numRooms] = current;
// Update floor tiles
for(uint256 y = current.y; y < current.y+current.height; y++) {
for(uint256 x = current.x; x < current.x+current.width; x++) {
floor = setBit(floor, y*settings.size+x); // Populate each bit of the room (from room[i]y -> room[i]y+h) to 1
}
}
numRooms--;
}
if(safetyCheck == 0) { // Make sure we don't enter an infinite loop trying to place rooms w/ no space
break;
}
safetyCheck--;
}
return (rooms, floor);
}
function generateCavern(Settings memory settings) internal view returns (uint256[] memory) {
// Tunneling - creates caves, mountains, etc.
uint256[] memory cavern = new uint256[](settings.length); // For this app we only need a length of 2; // Start with all walls (blank map)
uint256 lastDirection;
uint256 nextDirection;
uint256 x;
uint256 y;
// Cut out holes
uint256 holes = settings.size / 2;
for(uint256 i = 0; i < holes; i++) {
// Pick a randaom starting location
x = uint256(random(settings.seed << settings.counter++, 0, settings.size));
y = uint256(random(settings.seed << settings.counter++, 0, settings.size));
do {
// Cut current spot out of walls
setBit(cavern, y*settings.size + x);
if(lastDirection == 0) {
// This is our first time through, pick a random direction
nextDirection = uint256(random(settings.seed << settings.counter++, 1, 4));
lastDirection = nextDirection;
} else {
// We have a last direction so use weighted probability to determine where to go next
uint256 directionSeed = uint256(random(settings.seed << settings.counter++, 0, 100));
if(directionSeed <= 25) {
// Turn right
if(lastDirection == 3) {
nextDirection = 0; // (go back to first direction in our aray to avoid overflows)
} else {
nextDirection = lastDirection + 1;
}
} else if(directionSeed <= 50) {
// Turn left
if(lastDirection == 0) {
nextDirection = 3; // (go to the last direction in our array to avoid overflow)
} else {
nextDirection = lastDirection - 1;
}
} else {
// Keep moving forward in the same direction
nextDirection = lastDirection;
}
}
// if((x != 0 && nextDirection != 0) || (y != 0 && nextDirection != 3) || (x != settings.size && nextDirection != 1) || (y != settings.size && nextDirection != 1)) {
x = getDirection(x, directionsX[nextDirection]);
y = getDirection(y, directionsY[nextDirection]);
// }
} while (x > 0 && y > 0 && x < settings.size && y < settings.size); // Stop when we hit an edge
}
return(cavern);
}
function generateHallways(Settings memory settings, Room[] memory rooms) internal pure returns(uint256[] memory) {
// Connect each room with a hallway so we don't have hanging/floating rooms
// Number of hallways is always 1 less than number of rooms
uint256[] memory hallTiles = new uint256[](settings.length); // For this app we only need a length of 2;
// Only place hallways if we have more than one
if(rooms.length > 1) {
// Set first room as 'previous' (because we have to connect two rooms together)
uint256 previousX = rooms[0].x + (rooms[0].width / 2);
uint256 previousY = rooms[0].y + (rooms[0].height / 2);
for(uint256 i = 1; i < rooms.length; i++) {
uint256 currentX = rooms[i].x + (rooms[i].width / 2);
uint256 currentY = rooms[i].y + (rooms[i].height / 2);
// Figure out what type of hallway to place
if(currentX == previousX) {
// Rooms are lined up, make a vertical straight hallway
hallTiles = vHallway(settings.size, currentY, previousY, previousX, hallTiles);
} else if(currentY == previousY) {
// Rooms are lined up, make a horizontal straight hallway
hallTiles = hHallway(settings.size, currentX, previousX, previousY, hallTiles);
} else {
// Rooms aren't lined up so we need to draw two hallways
// Flip a coin to decide which we do first
// We need two hallways (w/ right angle)
if(random(settings.seed + settings.counter++, 1, 2) == 2) {
hallTiles = hHallway(settings.size, currentX, previousX, previousY, hallTiles);
hallTiles = vHallway(settings.size, previousY, currentY, currentX, hallTiles);
} else {
// Vertical first
hallTiles = vHallway(settings.size, currentY, previousY, previousX, hallTiles);
hallTiles = hHallway(settings.size, previousX, currentX, currentY, hallTiles);
}
}
previousX = currentX; // Process the next room
previousY = currentY;
}
}
return hallTiles;
}
function vHallway(uint256 size, uint256 y1, uint256 y2, uint256 x, uint256[] memory hallTiles) internal pure returns(uint256[] memory) {
// Draw a vertical tunnel from the center of one room to another (so x is always the same)
uint256 min = minimum(y1, y2);
uint256 max = maximum(y1, y2);
for(uint256 y = min; y < max; y++) {
// Place individual tiles
hallTiles = setBit(hallTiles, (y*size)+x); // Place a '0' for each hallway tile.
}
return hallTiles;
}
function hHallway(uint256 size, uint256 x1, uint256 x2, uint256 y, uint256[] memory hallTiles) internal pure returns(uint256[] memory ) {
// Draw a horizontal tunnel from the center of one room to another (so y is always the same)
uint256 min = minimum(x1, x2);
uint256 max = maximum(x1, x2);
for(uint256 x = min; x < max; x++) {
// Place individual tiles
hallTiles = setBit(hallTiles, (y*size)+x); // Place a '0' for each hallway tile.
}
return hallTiles;
}
function generatePoints(Settings memory settings, uint256[] memory map, uint256 probability) internal pure returns(uint256[] memory) {
uint256[] memory points = new uint256[](settings.length);
// Calculate max points based on floor tiles
uint256 prob = random(settings.seed + settings.counter++, 0, probability);
if(prob == 0) {
prob = 1; // Fix to avoid zero probability because solidity rounds down, not up so we do
}
uint256 counter = 0;
// Loop through each tile on the map
while(counter < settings.size ** 2) {
// Check if this is a floor tile (vs a wall)
if(getBit(map, counter) == 1) {
uint256 rand = random(settings.seed + settings.counter++, 0, 100);
if(rand <= prob) {
points = setBit(points, counter);
}
}
counter++;
}
return(points);
}
function countEntities(uint8[] memory entities) external pure returns(uint256, uint256) {
uint256 points = 0;
uint256 doors = 0;
for(uint256 i = 0; i < entities.length; i++) {
if(entities[i] == 0) {
points++;
} else {
doors++;
}
}
return(points, doors);
}
function parseEntities(uint256 size, uint256[] memory points, uint256[] memory doors) private pure returns(uint8[] memory, uint8[] memory, uint8[] memory) {
// Iterate through each map and returns an array for each entitiy type.
// 0 - Doors
// 1 - Points
uint256 entityCount = count(doors)+count(points);
uint8[] memory x = new uint8[](entityCount);
uint8[] memory y = new uint8[](entityCount);
uint8[] memory entityType = new uint8[](entityCount);
uint256 counter = 0;
// Shove points into arrays so we can return them
for(uint256 _y = 0; _y < size; _y++) {
for(uint256 _x = 0; _x < size; _x++) {
if(getBit(doors, counter) == 1) {
x[entityCount-1] = uint8(_x);
y[entityCount-1] = uint8(_y);
entityType[entityCount-1] = 0; // Hardcoded for doors
entityCount--;
}
if(getBit(points, counter) == 1) {
x[entityCount-1] = uint8(_x);
y[entityCount-1] = uint8(_y);
entityType[entityCount-1] = 1; // Hardcoded for points
entityCount--;
}
counter++;
}
}
return(x, y, entityType);
}
/* Utility Functions */
/* Bitwise Helper Functions (credit: cjpais) */
function getBit(uint256[] memory map, uint256 position) internal pure returns(uint256) {
// Returns whether a bit is set or off at a given position in our map
(uint256 quotient, uint256 remainder) = getDivided(position, 256);
require(position <= 255 + (quotient * 256));
return (map[quotient] >> (255 - remainder)) & 1;
}
function setBit(uint256[] memory map, uint256 position) internal pure returns(uint256[] memory) {
// Writes a wall bit (1) at a given position and returns the updated map
(uint256 quotient, uint256 remainder) = getDivided(position, 256);
require(position <= 255 + (quotient * 256));
map[quotient] = map[quotient] | (1 << (255 - remainder));
return (map);
}
function addBits(uint256[] memory first, uint256[] memory second) internal pure returns(uint256[] memory) {
// Combines two maps by 'OR'ing the two together
require(first.length == second.length);
for (uint256 i = 0; i < first.length; i++) {
first[i] = first[i] | second[i];
}
return first;
}
function subtractBits(uint256[] memory first, uint256[] memory second) internal pure returns(uint256[] memory) {
// Removes the second map from the first by 'AND'ing the two together
require(first.length == second.length);
for (uint256 i = 0; i < first.length; i++) {
first[i] = first[i] & ~(second[i]);
}
return first;
}
function toBytes(uint256[] memory map) internal pure returns (bytes memory) {
// Combines two maps into a single bytes array to be returned
bytes memory output;
for (uint256 i = 0; i < map.length; i++) {
output = abi.encodePacked(output, map[i]);
}
return output;
}
function count(uint256[] memory map) internal pure returns(uint256) {
// Function to count the total number of set bits in input (similar to an array .length)
// Uses Brian Kernighans algorithm
// Make a copy of the map so we don't clobber the original
uint256 curr;
uint256 result = 0;
for (uint256 i = 0; i < map.length; i++) {
curr = map[i];
while (curr != 0) {
curr = curr & (curr - 1);
result++;
}
}
return result;
}
function getDivided(uint256 numerator, uint256 denominator) public pure returns (uint256 quotient, uint256 remainder) {
// Divide - Return quotient and remainder
require(denominator > 0);
quotient = numerator / denominator;
remainder = numerator - denominator * quotient;
}
/* Dungeon directions */
function getDirection(uint256 pos, int8 direction) internal pure returns (uint256) {
// Helper function to map directions (because uint256/int8 can't be added / subtracted)
if(direction == 0) {
return(pos);
} else if(direction == 1) {
return(pos+1);
} else { // (direction == -1)
if(pos == 0) {
return(0); // Fix in case we try to move outside the bounds
}
return(pos-1);
}
}
function getLength(uint256 size) public pure returns (uint256) {
// Determine how many uint256's we need for our array
return ((size ** 2) / 256) + 1; // Always add 1 because solidity rounds down
}
/* RNG and Math Helper Functions */
function random(uint256 input, uint256 min, uint256 max) internal pure returns (uint256) {
// Returns a random (deterministic) seed between 0-range based on an arbitrary set of inputs
uint256 num;
if(max != min) {
num = max - min;
} else {
// max/min being the same causes modulo by zero error
num = 1;
}
uint256 output = uint256(keccak256(abi.encodePacked(input))) % (num) + min;
return output;
}
function maximum(uint256 one, uint256 two) internal pure returns(uint256 max) {
// Return the larger of two numbers
if(one > two) {
return one;
} else if(one <= two) {
return two;
}
}
function minimum(uint256 one, uint256 two) internal pure returns(uint256 min) {
// Return the smaller of two numbers
if(one > two) {
return two;
} else if(one <= two) {
return one;
}
}
function abs(uint256 one, uint256 two) internal pure returns(uint256 result) {
// Returns the absolute value of subtracting two numbers
if(one >= two) {
return(one - two);
} else {
return(two - one);
}
}
function sqrt(uint256 x) internal pure returns (uint256) {
// Returns the square root of a number
uint256 z = (x + 1) / 2;
uint256 y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
| Returns a byte array with each bit representing an entity tile on a map (e.g. point or doors) starting at 0,0/ | function getEntitiesBytes(uint256 seed, uint256 size) external view returns (bytes memory, bytes memory) {
(uint256[] memory points, uint256[] memory doors) = generateEntities(seed, size);
return (toBytes(points), toBytes(doors));
}
}
| 14,115,133 |
//Address: 0x2Ae024e4ECf78Ed1bf94eB3c7cF4E3e2ea03d550
//Contract name: SamsungToken
//Balance: 0 Ether
//Verification Date: 9/28/2017
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.11;
contract SamsungToken {
string public name;
string public symbol;
uint8 public decimals;
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
function SamsungToken() {
name = "SamsungToken";
symbol = "SamsungToken";
decimals = 2;
balanceOf[msg.sender] = 88800000000000;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
}
| This creates an array with all balances / | function SamsungToken() {
name = "SamsungToken";
symbol = "SamsungToken";
decimals = 2;
balanceOf[msg.sender] = 88800000000000;
}
| 6,346,844 |
// Sources flattened with hardhat v2.0.8 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
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 @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, basic interface
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is 0x80ac58cd.
*/
interface IERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* Gets the balance of the specified address
* @param owner address to query the balance of
* @return balance uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* Gets the owner of the specified ID
* @param tokenId uint256 ID to query the owner of
* @return owner address currently marked as the owner of the given ID
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) external;
/**
* Gets the approved address for a token ID, or zero if no address set
* @dev Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return operator address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* Safely transfers the ownership of a given token ID to another address
*
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* Safely transfers the ownership of a given token ID to another address
*
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is 0x5b5e139f.
*/
interface IERC721Metadata {
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory);
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory);
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
* @return string URI of given token ID
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, optional unsafe batchTransfer interface
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is.
*/
interface IERC721BatchTransfer {
/**
* Unsafely transfers a batch of tokens.
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `tokenIds` is not owned by `from`.
* @dev Resets the token approval for each of `tokenIds`.
* @dev Emits an {IERC721-Transfer} event for each of `tokenIds`.
* @param from Current tokens owner.
* @param to Address of the new token owner.
* @param tokenIds Identifiers of the tokens to transfer.
*/
function batchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
@title ERC721 Non-Fungible Token Standard, token receiver
@dev See https://eips.ethereum.org/EIPS/eip-721
Interface for any contract that wants to support safeTransfers from ERC721 asset contracts.
Note: The ERC-165 identifier for this interface is 0x150b7a02.
*/
interface IERC721Receiver {
/**
@notice Handle the receipt of an NFT
@dev The ERC721 smart contract calls this function on the recipient
after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
otherwise the caller will revert the transaction. The selector to be
returned can be obtained as `this.onERC721Received.selector`. This
function MAY throw to revert and reject the transfer.
Note: the ERC721 contract address is always the message sender.
@param operator The address which called `safeTransferFrom` function
@param from The address which previously owned the token
@param tokenId The NFT identifier which is being transferred
@param data Additional data with no specified format
@return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/GSN/[email protected]
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 @openzeppelin/contracts/introspection/[email protected]
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);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, basic interface
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
interface IERC1155 {
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _value, uint256 indexed _id);
/**
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Emits a `TransferSingle` event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to send along to a receiver contract.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
/**
* Safely transfers a batch of tokens.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `from` has an insufficient balance for any of `ids`.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits a `TransferBatch` event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to send along to a receiver contract.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
/**
* Retrieves the balance of `id` owned by account `owner`.
* @param owner The account to retrieve the balance of.
* @param id The identifier to retrieve the balance of.
* @return The balance of `id` owned by account `owner`.
*/
function balanceOf(address owner, uint256 id) external view returns (uint256);
/**
* Retrieves the balances of `ids` owned by accounts `owners`. For each pair:
* @dev Reverts if `owners` and `ids` have different lengths.
* @param owners The addresses of the token holders
* @param ids The identifiers to retrieve the balance of.
* @return The balances of `ids` owned by accounts `owners`.
*/
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* Enables or disables an operator's approval.
* @dev Emits an `ApprovalForAll` event.
* @param operator Address of the operator.
* @param approved True to approve the operator, false to revoke an approval.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* Retrieves the approval status of an operator for a given owner.
* @param owner Address of the authorisation giver.
* @param operator Address of the operator.
* @return True if the operator is approved, false if not.
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, optional metadata URI extension
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Note: The ERC-165 identifier for this interface is 0x0e89341c.
*/
interface IERC1155MetadataURI {
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* @dev The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
* @dev The uri function SHOULD be used to retrieve values if no event was emitted.
* @dev The uri function MUST return the same value as the latest event for an _id if it was emitted.
* @dev The uri function MUST NOT be used to check for the existence of a token as it is possible for
* an implementation to return a valid string even if the token does not exist.
* @return URI string
*/
function uri(uint256 id) external view returns (string memory);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, optional Inventory extension
* @dev See https://eips.ethereum.org/EIPS/eip-xxxx
* Interface for fungible/non-fungible tokens management on a 1155-compliant contract.
*
* This interface rationalizes the co-existence of fungible and non-fungible tokens
* within the same contract. As several kinds of fungible tokens can be managed under
* the Multi-Token standard, we consider that non-fungible tokens can be classified
* under their own specific type. We introduce the concept of non-fungible collection
* and consider the usage of 3 types of identifiers:
* (a) Fungible Token identifiers, each representing a set of Fungible Tokens,
* (b) Non-Fungible Collection identifiers, each representing a set of Non-Fungible Tokens (this is not a token),
* (c) Non-Fungible Token identifiers.
* Identifiers nature
* | Type | isFungible | isCollection | isToken |
* | Fungible Token | true | true | true |
* | Non-Fungible Collection | false | true | false |
* | Non-Fungible Token | false | false | true |
*
* Identifiers compatibilities
* | Type | transfer | balance | supply | owner |
* | Fungible Token | OK | OK | OK | NOK |
* | Non-Fungible Collection | NOK | OK | OK | NOK |
* | Non-Fungible Token | OK | 0 or 1 | 0 or 1 | OK |
*
* Note: The ERC-165 identifier for this interface is 0x469bd23f.
*/
interface IERC1155Inventory {
/**
* Optional event emitted when a collection (Fungible Token or Non-Fungible Collection) is created.
* This event can be used by a client application to determine which identifiers are meaningful
* to track through the functions `balanceOf`, `balanceOfBatch` and `totalSupply`.
* @dev This event MUST NOT be emitted twice for the same `collectionId`.
*/
event CollectionCreated(uint256 indexed collectionId, bool indexed fungible);
/**
* Retrieves the owner of a non-fungible token (ERC721-compatible).
* @dev Reverts if `nftId` is owned by the zero address.
* @param nftId Identifier of the token to query.
* @return Address of the current owner of the token.
*/
function ownerOf(uint256 nftId) external view returns (address);
/**
* Introspects whether or not `id` represents a fungible token.
* This function MUST return true even for a fungible token which is not-yet created.
* @param id The identifier to query.
* @return bool True if `id` represents afungible token, false otherwise.
*/
function isFungible(uint256 id) external pure returns (bool);
/**
* Introspects the non-fungible collection to which `nftId` belongs.
* @dev This function MUST return a value representing a non-fungible collection.
* @dev This function MUST return a value for a non-existing token, and SHOULD NOT be used to check the existence of a non-fungible token.
* @dev Reverts if `nftId` does not represent a non-fungible token.
* @param nftId The token identifier to query the collection of.
* @return The non-fungible collection identifier to which `nftId` belongs.
*/
function collectionOf(uint256 nftId) external pure returns (uint256);
/**
* Retrieves the total supply of `id`.
* @param id The identifier for which to retrieve the supply of.
* @return
* If `id` represents a collection (fungible token or non-fungible collection), the total supply for this collection.
* If `id` represents a non-fungible token, 1 if the token exists, else 0.
*/
function totalSupply(uint256 id) external view returns (uint256);
/**
* @notice this documentation overrides {IERC1155-balanceOf(address,uint256)}.
* Retrieves the balance of `id` owned by account `owner`.
* @param owner The account to retrieve the balance of.
* @param id The identifier to retrieve the balance of.
* @return
* If `id` represents a collection (fungible token or non-fungible collection), the balance for this collection.
* If `id` represents a non-fungible token, 1 if the token is owned by `owner`, else 0.
*/
// function balanceOf(address owner, uint256 id) external view returns (uint256);
/**
* @notice this documentation overrides {IERC1155-balanceOfBatch(address[],uint256[])}.
* Retrieves the balances of `ids` owned by accounts `owners`.
* @dev Reverts if `owners` and `ids` have different lengths.
* @param owners The accounts to retrieve the balances of.
* @param ids The identifiers to retrieve the balances of.
* @return An array of elements such as for each pair `id`/`owner`:
* If `id` represents a collection (fungible token or non-fungible collection), the balance for this collection.
* If `id` represents a non-fungible token, 1 if the token is owned by `owner`, else 0.
*/
// function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @notice this documentation overrides its {IERC1155-safeTransferFrom(address,address,uint256,uint256,bytes)}.
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `id` does not represent a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 id,
// uint256 value,
// bytes calldata data
// ) external;
/**
* @notice this documentation overrides its {IERC1155-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
* Safely transfers a batch of tokens.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `ids` does not represent a token.
* @dev Reverts if one of `ids` represents a non-fungible token and `value` is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if one of `ids` represents a fungible token and `value` is 0.
* @dev Reverts if one of `ids` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if one of `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits an {IERC1155-TransferBatch} event.
* @param from Current tokens owner.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeBatchTransferFrom(
// address from,
// address to,
// uint256[] calldata ids,
// uint256[] calldata values,
// bytes calldata data
// ) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, token receiver
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Interface for any contract that wants to support transfers from ERC1155 asset contracts.
* Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type.
* An ERC1155 contract MUST call this function on a recipient contract, at the end of a `safeTransferFrom` after the balance update.
* This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61) to accept the transfer.
* Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types.
* An ERC1155 contract MUST call this function on a recipient contract, at the end of a `safeBatchTransferFrom` after the balance updates.
* This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81) if to accept the transfer(s).
* Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match _values array)
* @param values An array containing amounts of each token being transferred (order and length must match _ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC1155InventoryIdentifiersLib, a library to introspect inventory identifiers.
* @dev With N=32, representing the Non-Fungible Collection mask length, identifiers are represented as follow:
* (a) a Fungible Token:
* - most significant bit == 0
* (b) a Non-Fungible Collection:
* - most significant bit == 1
* - (256-N) least significant bits == 0
* (c) a Non-Fungible Token:
* - most significant bit == 1
* - (256-N) least significant bits != 0
*/
library ERC1155InventoryIdentifiersLib {
// Non-fungible bit. If an id has this bit set, it is a non-fungible (either collection or token)
uint256 internal constant _NF_BIT = 1 << 255;
// Mask for non-fungible collection (including the nf bit)
uint256 internal constant _NF_COLLECTION_MASK = uint256(type(uint32).max) << 224;
uint256 internal constant _NF_TOKEN_MASK = ~_NF_COLLECTION_MASK;
function isFungibleToken(uint256 id) internal pure returns (bool) {
return id & _NF_BIT == 0;
}
function isNonFungibleToken(uint256 id) internal pure returns (bool) {
return id & _NF_BIT != 0 && id & _NF_TOKEN_MASK != 0;
}
function getNonFungibleCollection(uint256 nftId) internal pure returns (uint256) {
return nftId & _NF_COLLECTION_MASK;
}
}
abstract contract ERC1155InventoryBase is IERC1155, IERC1155MetadataURI, IERC1155Inventory, IERC165, Context {
using ERC1155InventoryIdentifiersLib for uint256;
bytes4 private constant _ERC165_INTERFACE_ID = type(IERC165).interfaceId;
bytes4 private constant _ERC1155_INTERFACE_ID = type(IERC1155).interfaceId;
bytes4 private constant _ERC1155_METADATA_URI_INTERFACE_ID = type(IERC1155MetadataURI).interfaceId;
bytes4 private constant _ERC1155_INVENTORY_INTERFACE_ID = type(IERC1155Inventory).interfaceId;
// bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 internal constant _ERC1155_RECEIVED = 0xf23a6e61;
// bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
bytes4 internal constant _ERC1155_BATCH_RECEIVED = 0xbc197c81;
// Burnt non-fungible token owner's magic value
uint256 internal constant _BURNT_NFT_OWNER = 0xdead000000000000000000000000000000000000000000000000000000000000;
/* owner => operator => approved */
mapping(address => mapping(address => bool)) internal _operators;
/* collection ID => owner => balance */
mapping(uint256 => mapping(address => uint256)) internal _balances;
/* collection ID => supply */
mapping(uint256 => uint256) internal _supplies;
/* NFT ID => owner */
mapping(uint256 => uint256) internal _owners;
/* collection ID => creator */
mapping(uint256 => address) internal _creators;
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == _ERC165_INTERFACE_ID ||
interfaceId == _ERC1155_INTERFACE_ID ||
interfaceId == _ERC1155_METADATA_URI_INTERFACE_ID ||
interfaceId == _ERC1155_INVENTORY_INTERFACE_ID;
}
//================================== ERC1155 =======================================/
/// @dev See {IERC1155-balanceOf(address,uint256)}.
function balanceOf(address owner, uint256 id) public view virtual override returns (uint256) {
require(owner != address(0), "Inventory: zero address");
if (id.isNonFungibleToken()) {
return address(_owners[id]) == owner ? 1 : 0;
}
return _balances[id][owner];
}
/// @dev See {IERC1155-balanceOfBatch(address[],uint256[])}.
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view virtual override returns (uint256[] memory) {
require(owners.length == ids.length, "Inventory: inconsistent arrays");
uint256[] memory balances = new uint256[](owners.length);
for (uint256 i = 0; i != owners.length; ++i) {
balances[i] = balanceOf(owners[i], ids[i]);
}
return balances;
}
/// @dev See {IERC1155-setApprovalForAll(address,bool)}.
function setApprovalForAll(address operator, bool approved) public virtual override {
address sender = _msgSender();
require(operator != sender, "Inventory: self-approval");
_operators[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/// @dev See {IERC1155-isApprovedForAll(address,address)}.
function isApprovedForAll(address tokenOwner, address operator) public view virtual override returns (bool) {
return _operators[tokenOwner][operator];
}
//================================== ERC1155Inventory =======================================/
/// @dev See {IERC1155Inventory-isFungible(uint256)}.
function isFungible(uint256 id) external pure virtual override returns (bool) {
return id.isFungibleToken();
}
/// @dev See {IERC1155Inventory-collectionOf(uint256)}.
function collectionOf(uint256 nftId) external pure virtual override returns (uint256) {
require(nftId.isNonFungibleToken(), "Inventory: not an NFT");
return nftId.getNonFungibleCollection();
}
/// @dev See {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) public view virtual override returns (address) {
address owner = address(_owners[nftId]);
require(owner != address(0), "Inventory: non-existing NFT");
return owner;
}
/// @dev See {IERC1155Inventory-totalSupply(uint256)}.
function totalSupply(uint256 id) external view virtual override returns (uint256) {
if (id.isNonFungibleToken()) {
return address(_owners[id]) == address(0) ? 0 : 1;
} else {
return _supplies[id];
}
}
//================================== ABI-level Internal Functions =======================================/
/**
* Creates a collection (optional).
* @dev Reverts if `collectionId` does not represent a collection.
* @dev Reverts if `collectionId` has already been created.
* @dev Emits a {IERC1155Inventory-CollectionCreated} event.
* @param collectionId Identifier of the collection.
*/
function _createCollection(uint256 collectionId) internal virtual {
require(!collectionId.isNonFungibleToken(), "Inventory: not a collection");
require(_creators[collectionId] == address(0), "Inventory: existing collection");
_creators[collectionId] = _msgSender();
emit CollectionCreated(collectionId, collectionId.isFungibleToken());
}
/// @dev See {IERC1155InventoryCreator-creator(uint256)}.
function _creator(uint256 collectionId) internal view virtual returns (address) {
require(!collectionId.isNonFungibleToken(), "Inventory: not a collection");
return _creators[collectionId];
}
//================================== Internal Helper Functions =======================================/
/**
* Returns whether `sender` is authorised to make a transfer on behalf of `from`.
* @param from The address to check operatibility upon.
* @param sender The sender address.
* @return True if sender is `from` or an operator for `from`, false otherwise.
*/
function _isOperatable(address from, address sender) internal view virtual returns (bool) {
return (from == sender) || _operators[from][sender];
}
/**
* Calls {IERC1155TokenReceiver-onERC1155Received} on a target contract.
* @dev Reverts if `to` is not a contract.
* @dev Reverts if the call to the target fails or is refused.
* @param from Previous token owner.
* @param to New token owner.
* @param id Identifier of the token transferred.
* @param value Amount of token transferred.
* @param data Optional data to send along with the receiver contract call.
*/
function _callOnERC1155Received(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) internal {
require(IERC1155TokenReceiver(to).onERC1155Received(_msgSender(), from, id, value, data) == _ERC1155_RECEIVED, "Inventory: transfer refused");
}
/**
* Calls {IERC1155TokenReceiver-onERC1155batchReceived} on a target contract.
* @dev Reverts if `to` is not a contract.
* @dev Reverts if the call to the target fails or is refused.
* @param from Previous tokens owner.
* @param to New tokens owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to send along with the receiver contract call.
*/
function _callOnERC1155BatchReceived(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
require(
IERC1155TokenReceiver(to).onERC1155BatchReceived(_msgSender(), from, ids, values, data) == _ERC1155_BATCH_RECEIVED,
"Inventory: transfer refused"
);
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC1155721Inventory, an ERC1155Inventory with additional support for ERC721.
*/
abstract contract ERC1155721Inventory is IERC721, IERC721Metadata, IERC721BatchTransfer, ERC1155InventoryBase {
using Address for address;
bytes4 private constant _ERC165_INTERFACE_ID = type(IERC165).interfaceId;
bytes4 private constant _ERC1155_TOKEN_RECEIVER_INTERFACE_ID = type(IERC1155TokenReceiver).interfaceId;
bytes4 private constant _ERC721_INTERFACE_ID = type(IERC721).interfaceId;
bytes4 private constant _ERC721_METADATA_INTERFACE_ID = type(IERC721Metadata).interfaceId;
bytes4 internal constant _ERC721_RECEIVED = type(IERC721Receiver).interfaceId;
uint256 internal constant _APPROVAL_BIT_TOKEN_OWNER_ = 1 << 160;
/* owner => NFT balance */
mapping(address => uint256) internal _nftBalances;
/* NFT ID => operator */
mapping(uint256 => address) internal _nftApprovals;
/// @dev See {IERC165-supportsInterface(bytes4)}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || interfaceId == _ERC721_INTERFACE_ID || interfaceId == _ERC721_METADATA_INTERFACE_ID;
}
//===================================== ERC721 ==========================================/
/// @dev See {IERC721-balanceOf(address)}.
function balanceOf(address tokenOwner) external view virtual override returns (uint256) {
require(tokenOwner != address(0), "Inventory: zero address");
return _nftBalances[tokenOwner];
}
/// @dev See {IERC721-ownerOf(uint256)} and {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) public view virtual override(IERC721, ERC1155InventoryBase) returns (address) {
return ERC1155InventoryBase.ownerOf(nftId);
}
/// @dev See {IERC721-approve(address,uint256)}.
function approve(address to, uint256 nftId) external virtual override {
address tokenOwner = ownerOf(nftId);
require(to != tokenOwner, "Inventory: self-approval");
require(_isOperatable(tokenOwner, _msgSender()), "Inventory: non-approved sender");
_owners[nftId] = uint256(tokenOwner) | _APPROVAL_BIT_TOKEN_OWNER_;
_nftApprovals[nftId] = to;
emit Approval(tokenOwner, to, nftId);
}
/// @dev See {IERC721-getApproved(uint256)}.
function getApproved(uint256 nftId) external view virtual override returns (address) {
uint256 tokenOwner = _owners[nftId];
require(address(tokenOwner) != address(0), "Inventory: non-existing NFT");
if (tokenOwner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) {
return _nftApprovals[nftId];
} else {
return address(0);
}
}
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function isApprovedForAll(address tokenOwner, address operator) public view virtual override(IERC721, ERC1155InventoryBase) returns (bool) {
return ERC1155InventoryBase.isApprovedForAll(tokenOwner, operator);
}
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function setApprovalForAll(address operator, bool approved) public virtual override(IERC721, ERC1155InventoryBase) {
return ERC1155InventoryBase.setApprovalForAll(operator, approved);
}
/**
* Unsafely transfers a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721Inventory-transferFrom(address,address,uint256)}.
*/
function transferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
_transferFrom(
from,
to,
nftId,
"",
/* safe */
false
);
}
/**
* Safely transfers a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721Inventory-safeTransferFrom(address,address,uint256)}.
*/
function safeTransferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
_transferFrom(
from,
to,
nftId,
"",
/* safe */
true
);
}
/**
* Safely transfers a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721Inventory-safeTransferFrom(address,address,uint256,bytes)}.
*/
function safeTransferFrom(
address from,
address to,
uint256 nftId,
bytes memory data
) public virtual override {
_transferFrom(
from,
to,
nftId,
data,
/* safe */
true
);
}
/**
* Unsafely transfers a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721BatchTransfer-batchTransferFrom(address,address,uint256[])}.
*/
function batchTransferFrom(
address from,
address to,
uint256[] memory nftIds
) public virtual override {
require(to != address(0), "Inventory: transfer to zero");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 length = nftIds.length;
uint256[] memory values = new uint256[](length);
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 nftId = nftIds[i];
values[i] = 1;
_transferNFT(from, to, nftId, 1, operatable, true);
emit Transfer(from, to, nftId);
uint256 nextCollectionId = nftId.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
}
if (nfCollectionId != 0) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
_transferNFTUpdateBalances(from, to, length);
}
emit TransferBatch(_msgSender(), from, to, nftIds, values);
if (to.isContract() && _isERC1155TokenReceiver(to)) {
_callOnERC1155BatchReceived(from, to, nftIds, values, "");
}
}
/// @dev See {IERC721Metadata-tokenURI(uint256)}.
function tokenURI(uint256 nftId) external view virtual override returns (string memory) {
require(address(_owners[nftId]) != address(0), "Inventory: non-existing NFT");
return uri(nftId);
}
//================================== ERC1155 =======================================/
/**
* Safely transfers some token (ERC1155-compatible).
* @dev See {IERC1155721Inventory-safeTransferFrom(address,address,uint256,uint256,bytes)}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
address sender = _msgSender();
require(to != address(0), "Inventory: transfer to zero");
bool operatable = _isOperatable(from, sender);
if (id.isFungibleToken()) {
_transferFungible(from, to, id, value, operatable);
} else if (id.isNonFungibleToken()) {
_transferNFT(from, to, id, value, operatable, false);
emit Transfer(from, to, id);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, to, id, value);
if (to.isContract()) {
_callOnERC1155Received(from, to, id, value, data);
}
}
/**
* Safely transfers a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
// internal function to avoid stack too deep error
_safeBatchTransferFrom(from, to, ids, values, data);
}
//================================== ERC1155MetadataURI =======================================/
/// @dev See {IERC1155MetadataURI-uri(uint256)}.
function uri(uint256) public view virtual override returns (string memory);
//================================== ABI-level Internal Functions =======================================/
/**
* Safely or unsafely transfers some token (ERC721-compatible).
* @dev For `safe` transfer, see {IERC1155721Inventory-transferFrom(address,address,uint256)}.
* @dev For un`safe` transfer, see {IERC1155721Inventory-safeTransferFrom(address,address,uint256,bytes)}.
*/
function _transferFrom(
address from,
address to,
uint256 nftId,
bytes memory data,
bool safe
) internal {
require(to != address(0), "Inventory: transfer to zero");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
_transferNFT(from, to, nftId, 1, operatable, false);
emit Transfer(from, to, nftId);
emit TransferSingle(sender, from, to, nftId, 1);
if (to.isContract()) {
if (_isERC1155TokenReceiver(to)) {
_callOnERC1155Received(from, to, nftId, 1, data);
} else if (safe) {
_callOnERC721Received(from, to, nftId, data);
}
}
}
/**
* Safely transfers a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
require(to != address(0), "Inventory: transfer to zero");
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 nfCollectionId;
uint256 nfCollectionCount;
uint256 nftsCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
if (id.isFungibleToken()) {
_transferFungible(from, to, id, values[i], operatable);
} else if (id.isNonFungibleToken()) {
_transferNFT(from, to, id, values[i], operatable, true);
emit Transfer(from, to, id);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nftsCount += nfCollectionCount;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
nftsCount += nfCollectionCount;
_transferNFTUpdateBalances(from, to, nftsCount);
}
emit TransferBatch(_msgSender(), from, to, ids, values);
if (to.isContract()) {
_callOnERC1155BatchReceived(from, to, ids, values, data);
}
}
/**
* Safely or unsafely mints some token (ERC721-compatible).
* @dev For `safe` mint, see {IERC1155721InventoryMintable-mint(address,uint256)}.
* @dev For un`safe` mint, see {IERC1155721InventoryMintable-safeMint(address,uint256,bytes)}.
*/
function _mint(
address to,
uint256 nftId,
bytes memory data,
bool safe
) internal {
require(to != address(0), "Inventory: transfer to zero");
require(nftId.isNonFungibleToken(), "Inventory: not an NFT");
_mintNFT(to, nftId, 1, false);
emit Transfer(address(0), to, nftId);
emit TransferSingle(_msgSender(), address(0), to, nftId, 1);
if (to.isContract()) {
if (_isERC1155TokenReceiver(to)) {
_callOnERC1155Received(address(0), to, nftId, 1, data);
} else if (safe) {
_callOnERC721Received(address(0), to, nftId, data);
}
}
}
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256[])}.
*/
function _batchMint(address to, uint256[] memory nftIds) internal {
require(to != address(0), "Inventory: transfer to zero");
uint256 length = nftIds.length;
uint256[] memory values = new uint256[](length);
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 nftId = nftIds[i];
require(nftId.isNonFungibleToken(), "Inventory: not an NFT");
values[i] = 1;
_mintNFT(to, nftId, 1, true);
emit Transfer(address(0), to, nftId);
uint256 nextCollectionId = nftId.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
}
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
_nftBalances[to] += length;
emit TransferBatch(_msgSender(), address(0), to, nftIds, values);
if (to.isContract() && _isERC1155TokenReceiver(to)) {
_callOnERC1155BatchReceived(address(0), to, nftIds, values, "");
}
}
/**
* Safely mints some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}.
*/
function _safeMint(
address to,
uint256 id,
uint256 value,
bytes memory data
) internal virtual {
require(to != address(0), "Inventory: transfer to zero");
address sender = _msgSender();
if (id.isFungibleToken()) {
_mintFungible(to, id, value);
} else if (id.isNonFungibleToken()) {
_mintNFT(to, id, value, false);
emit Transfer(address(0), to, id);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, address(0), to, id, value);
if (to.isContract()) {
_callOnERC1155Received(address(0), to, id, value, data);
}
}
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeBatchMint(address,uint256[],uint256[],bytes)}.
*/
function _safeBatchMint(
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal virtual {
require(to != address(0), "Inventory: transfer to zero");
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
uint256 nfCollectionId;
uint256 nfCollectionCount;
uint256 nftsCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_mintFungible(to, id, value);
} else if (id.isNonFungibleToken()) {
_mintNFT(to, id, value, true);
emit Transfer(address(0), to, id);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
nfCollectionId = nextCollectionId;
nftsCount += nfCollectionCount;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
nftsCount += nfCollectionCount;
_nftBalances[to] += nftsCount;
}
emit TransferBatch(_msgSender(), address(0), to, ids, values);
if (to.isContract()) {
_callOnERC1155BatchReceived(address(0), to, ids, values, data);
}
}
//============================== Internal Helper Functions =======================================/
function _mintFungible(
address to,
uint256 id,
uint256 value
) internal {
require(value != 0, "Inventory: zero value");
uint256 supply = _supplies[id];
uint256 newSupply = supply + value;
require(newSupply > supply, "Inventory: supply overflow");
_supplies[id] = newSupply;
// cannot overflow as supply cannot overflow
_balances[id][to] += value;
}
function _mintNFT(
address to,
uint256 id,
uint256 value,
bool isBatch
) internal {
require(value == 1, "Inventory: wrong NFT value");
require(_owners[id] == 0, "Inventory: existing/burnt NFT");
_owners[id] = uint256(to);
if (!isBatch) {
uint256 collectionId = id.getNonFungibleCollection();
// it is virtually impossible that a non-fungible collection supply
// overflows due to the cost of minting individual tokens
++_supplies[collectionId];
++_balances[collectionId][to];
++_nftBalances[to];
}
}
function _transferFungible(
address from,
address to,
uint256 id,
uint256 value,
bool operatable
) internal {
require(operatable, "Inventory: non-approved sender");
require(value != 0, "Inventory: zero value");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
if (from != to) {
_balances[id][from] = balance - value;
// cannot overflow as supply cannot overflow
_balances[id][to] += value;
}
}
function _transferNFT(
address from,
address to,
uint256 id,
uint256 value,
bool operatable,
bool isBatch
) internal virtual {
require(value == 1, "Inventory: wrong NFT value");
uint256 owner = _owners[id];
require(from == address(owner), "Inventory: non-owned NFT");
if (!operatable) {
require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[id], "Inventory: non-approved sender");
}
_owners[id] = uint256(to);
if (!isBatch) {
_transferNFTUpdateBalances(from, to, 1);
_transferNFTUpdateCollection(from, to, id.getNonFungibleCollection(), 1);
}
}
function _transferNFTUpdateBalances(
address from,
address to,
uint256 amount
) internal virtual {
if (from != to) {
// cannot underflow as balance is verified through ownership
_nftBalances[from] -= amount;
// cannot overflow as supply cannot overflow
_nftBalances[to] += amount;
}
}
function _transferNFTUpdateCollection(
address from,
address to,
uint256 collectionId,
uint256 amount
) internal virtual {
if (from != to) {
// cannot underflow as balance is verified through ownership
_balances[collectionId][from] -= amount;
// cannot overflow as supply cannot overflow
_balances[collectionId][to] += amount;
}
}
///////////////////////////////////// Receiver Calls Internal /////////////////////////////////////
/**
* Queries whether a contract implements ERC1155TokenReceiver.
* @param _contract address of the contract.
* @return wheter the given contract implements ERC1155TokenReceiver.
*/
function _isERC1155TokenReceiver(address _contract) internal view returns (bool) {
bool success;
bool result;
bytes memory staticCallData = abi.encodeWithSelector(_ERC165_INTERFACE_ID, _ERC1155_TOKEN_RECEIVER_INTERFACE_ID);
assembly {
let call_ptr := add(0x20, staticCallData)
let call_size := mload(staticCallData)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(10000, _contract, call_ptr, call_size, output, 0x20) // 32 bytes
result := mload(output)
}
// (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas
assert(gasleft() > 158);
return success && result;
}
/**
* Calls {IERC721Receiver-onERC721Received} on a target contract.
* @dev Reverts if `to` is not a contract.
* @dev Reverts if the call to the target fails or is refused.
* @param from Previous token owner.
* @param to New token owner.
* @param nftId Identifier of the token transferred.
* @param data Optional data to send along with the receiver contract call.
*/
function _callOnERC721Received(
address from,
address to,
uint256 nftId,
bytes memory data
) internal {
require(IERC721Receiver(to).onERC721Received(_msgSender(), from, nftId, data) == _ERC721_RECEIVED, "Inventory: transfer refused");
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title IERC1155721InventoryBurnable interface.
* The function {IERC721Burnable-burnFrom(address,uint256)} is not provided as
* {IERC1155Burnable-burnFrom(address,uint256,uint256)} can be used instead.
*/
interface IERC1155721InventoryBurnable {
/**
* Burns some token (ERC1155-compatible).
* @dev Reverts if the sender is not approved.
* @dev Reverts if `id` does not represent a token.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and `value` is higher than `from`'s balance.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token which is not owned by `from`.
* @dev Emits an {IERC721-Transfer} event to the zero address if `id` represents a non-fungible token.
* @dev Emits an {IERC1155-TransferSingle} event to the zero address.
* @param from Address of the current token owner.
* @param id Identifier of the token to burn.
* @param value Amount of token to burn.
*/
function burnFrom(
address from,
uint256 id,
uint256 value
) external;
/**
* Burns multiple tokens (ERC1155-compatible).
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `ids` does not represent a token.
* @dev Reverts if one of `ids` represents a fungible token and `value` is 0.
* @dev Reverts if one of `ids` represents a fungible token and `value` is higher than `from`'s balance.
* @dev Reverts if one of `ids` represents a non-fungible token and `value` is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token which is not owned by `from`.
* @dev Emits an {IERC721-Transfer} event to the zero address for each burnt non-fungible token.
* @dev Emits an {IERC1155-TransferBatch} event to the zero address.
* @param from Address of the current tokens owner.
* @param ids Identifiers of the tokens to burn.
* @param values Amounts of tokens to burn.
*/
function batchBurnFrom(
address from,
uint256[] calldata ids,
uint256[] calldata values
) external;
/**
* Burns a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `nftIds` does not represent a non-fungible token.
* @dev Reverts if one of `nftIds` is not owned by `from`.
* @dev Emits an {IERC721-Transfer} event to the zero address for each of `nftIds`.
* @dev Emits an {IERC1155-TransferBatch} event to the zero address.
* @param from Current token owner.
* @param nftIds Identifiers of the tokens to transfer.
*/
function batchBurnFrom(address from, uint256[] calldata nftIds) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC1155721InventoryBurnable, a burnable ERC1155721Inventory.
*/
abstract contract ERC1155721InventoryBurnable is IERC1155721InventoryBurnable, ERC1155721Inventory {
//============================== ERC1155721InventoryBurnable =======================================/
/**
* Burns some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryBurnable-burnFrom(address,uint256,uint256)}.
*/
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
if (id.isFungibleToken()) {
_burnFungible(from, id, value, operatable);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, value, operatable, false);
emit Transfer(from, address(0), id);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, address(0), id, value);
}
/**
* Burns a batch of token (ERC1155-compatible).
* @dev See {IERC1155721InventoryBurnable-batchBurnFrom(address,uint256[],uint256[])}.
*/
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 nfCollectionId;
uint256 nfCollectionCount;
uint256 nftsCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, values[i], operatable);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, values[i], operatable, true);
emit Transfer(from, address(0), id);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nftsCount += nfCollectionCount;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
nftsCount += nfCollectionCount;
// cannot underflow as balance is verified through ownership
_nftBalances[from] -= nftsCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
/**
* Burns a batch of token (ERC721-compatible).
* @dev See {IERC1155721InventoryBurnable-batchBurnFrom(address,uint256[])}.
*/
function batchBurnFrom(address from, uint256[] memory nftIds) public virtual override {
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 length = nftIds.length;
uint256[] memory values = new uint256[](length);
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 nftId = nftIds[i];
values[i] = 1;
_burnNFT(from, nftId, values[i], operatable, true);
emit Transfer(from, address(0), nftId);
uint256 nextCollectionId = nftId.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
}
if (nfCollectionId != 0) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
_nftBalances[from] -= length;
}
emit TransferBatch(sender, from, address(0), nftIds, values);
}
//============================== Internal Helper Functions =======================================/
function _burnFungible(
address from,
uint256 id,
uint256 value,
bool operatable
) internal {
require(value != 0, "Inventory: zero value");
require(operatable, "Inventory: non-approved sender");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
_balances[id][from] = balance - value;
// Cannot underflow
_supplies[id] -= value;
}
function _burnNFT(
address from,
uint256 id,
uint256 value,
bool operatable,
bool isBatch
) internal virtual {
require(value == 1, "Inventory: wrong NFT value");
uint256 owner = _owners[id];
require(from == address(owner), "Inventory: non-owned NFT");
if (!operatable) {
require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[id], "Inventory: non-approved sender");
}
_owners[id] = _BURNT_NFT_OWNER;
if (!isBatch) {
_burnNFTUpdateCollection(from, id.getNonFungibleCollection(), 1);
// cannot underflow as balance is verified through NFT ownership
--_nftBalances[from];
}
}
function _burnNFTUpdateCollection(
address from,
uint256 collectionId,
uint256 amount
) internal virtual {
// cannot underflow as balance is verified through NFT ownership
_balances[collectionId][from] -= amount;
_supplies[collectionId] -= amount;
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title IERC1155721InventoryMintable interface.
* The function {IERC721Mintable-safeMint(address,uint256,bytes)} is not provided as
* {IERC1155Mintable-safeMint(address,uint256,uint256,bytes)} can be used instead.
*/
interface IERC1155721InventoryMintable {
/**
* Safely mints some token (ERC1155-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `id` is not a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token which has already been minted.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and there is an overflow of supply.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155Received} fails or is refused.
* @dev Emits an {IERC721-Transfer} event from the zero address if `id` represents a non-fungible token.
* @dev Emits an {IERC1155-TransferSingle} event from the zero address.
* @param to Address of the new token owner.
* @param id Identifier of the token to mint.
* @param value Amount of token to mint.
* @param data Optional data to send along to a receiver contract.
*/
function safeMint(
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if one of `ids` is not a token.
* @dev Reverts if one of `ids` represents a non-fungible token and its paired value is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token which has already been minted.
* @dev Reverts if one of `ids` represents a fungible token and its paired value is 0.
* @dev Reverts if one of `ids` represents a fungible token and there is an overflow of supply.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits an {IERC721-Transfer} event from the zero address for each non-fungible token minted.
* @dev Emits an {IERC1155-TransferBatch} event from the zero address.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to mint.
* @param values Amounts of tokens to mint.
* @param data Optional data to send along to a receiver contract.
*/
function safeBatchMint(
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
/**
* Unsafely mints a Non-Fungible Token (ERC721-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `nftId` does not represent a non-fungible token.
* @dev Reverts if `nftId` has already been minted.
* @dev Emits an {IERC721-Transfer} event from the zero address.
* @dev Emits an {IERC1155-TransferSingle} event from the zero address.
* @dev If `to` is a contract and supports ERC1155TokenReceiver, calls {IERC1155TokenReceiver-onERC1155Received} with empty data.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to mint.
*/
function mint(address to, uint256 nftId) external;
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if one of `nftIds` does not represent a non-fungible token.
* @dev Reverts if one of `nftIds` has already been minted.
* @dev Emits an {IERC721-Transfer} event from the zero address for each of `nftIds`.
* @dev Emits an {IERC1155-TransferBatch} event from the zero address.
* @dev If `to` is a contract and supports ERC1155TokenReceiver, calls {IERC1155TokenReceiver-onERC1155BatchReceived} with empty data.
* @param to Address of the new token owner.
* @param nftIds Identifiers of the tokens to mint.
*/
function batchMint(address to, uint256[] calldata nftIds) external;
/**
* Safely mints a token (ERC721-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `tokenId` has already ben minted.
* @dev Reverts if `to` is a contract which does not implement IERC721Receiver or IERC1155TokenReceiver.
* @dev Reverts if `to` is an IERC1155TokenReceiver or IERC721TokenReceiver contract which refuses the transfer.
* @dev Emits an {IERC721-Transfer} event from the zero address.
* @dev Emits an {IERC1155-TransferSingle} event from the zero address.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to mint.
* @param data Optional data to pass along to the receiver call.
*/
function safeMint(
address to,
uint256 nftId,
bytes calldata data
) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Inventory, additional creator interface
* @dev See https://eips.ethereum.org/EIPS/eip-1155
*/
interface IERC1155InventoryCreator {
/**
* Returns the creator of a collection, or the zero address if the collection has not been created.
* @dev Reverts if `collectionId` does not represent a collection.
* @param collectionId Identifier of the collection.
* @return The creator of a collection, or the zero address if the collection has not been created.
*/
function creator(uint256 collectionId) external view returns (address);
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @animoca/ethereum-contracts-core_library/contracts/utils/types/[email protected]
pragma solidity 0.6.8;
library UInt256ToDecimalString {
function toDecimalString(uint256 value) internal pure returns (string memory) {
// Inspired by OpenZeppelin's String.toString() implementation - MIT licence
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/8b10cb38d8fedf34f2d89b0ed604f2dceb76d6a9/contracts/utils/Strings.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/metadata/[email protected]
pragma solidity 0.6.8;
contract BaseMetadataURI is Ownable {
using UInt256ToDecimalString for uint256;
event BaseMetadataURISet(string baseMetadataURI);
string public baseMetadataURI;
function setBaseMetadataURI(string calldata baseMetadataURI_) external onlyOwner {
baseMetadataURI = baseMetadataURI_;
emit BaseMetadataURISet(baseMetadataURI_);
}
function _uri(uint256 id) internal view virtual returns (string memory) {
return string(abi.encodePacked(baseMetadataURI, id.toDecimalString()));
}
}
// File @openzeppelin/contracts/utils/[email protected]
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(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @animoca/ethereum-contracts-core_library/contracts/access/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts access control over token
* minting operations.
*
* This module is used through inheritance. It will make available the modifier
* `onlyMinter`, which can be applied to the minting functions of your contract.
* Those functions will only be accessible to accounts with the minter role
* once the modifer is put in place.
*/
contract MinterRole is AccessControl {
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
/**
* Modifier to make a function callable only by accounts with the minter role.
*/
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: not a Minter");
_;
}
/**
* Constructor.
*/
constructor() internal {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
emit MinterAdded(_msgSender());
}
/**
* Validates whether or not the given account has been granted the minter role.
* @param account The account to validate.
* @return True if the account has been granted the minter role, false otherwise.
*/
function isMinter(address account) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
/**
* Grants the minter role to a non-minter.
* @param account The account to grant the minter role to.
*/
function addMinter(address account) public onlyMinter {
require(!isMinter(account), "MinterRole: already Minter");
grantRole(DEFAULT_ADMIN_ROLE, account);
emit MinterAdded(account);
}
/**
* Renounces the granted minter role.
*/
function renounceMinter() public onlyMinter {
renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
emit MinterRemoved(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract 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 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());
}
}
// File contracts/solc-0.6/token/ERC1155721/REVVInventory.sol
pragma solidity ^0.6.8;
contract REVVInventory is
Ownable,
Pausable,
ERC1155721InventoryBurnable,
IERC1155721InventoryMintable,
IERC1155InventoryCreator,
BaseMetadataURI,
MinterRole
{
// solhint-disable-next-line const-name-snakecase
string public constant override name = "REVV Inventory";
// solhint-disable-next-line const-name-snakecase
string public constant override symbol = "REVV-I";
//================================== ERC1155MetadataURI =======================================/
/// @dev See {IERC1155MetadataURI-uri(uint256)}.
function uri(uint256 id) public view virtual override returns (string memory) {
return _uri(id);
}
//================================== ERC1155InventoryCreator =======================================/
/// @dev See {IERC1155InventoryCreator-creator(uint256)}.
function creator(uint256 collectionId) external view override returns (address) {
return _creator(collectionId);
}
// ===================================================================================================
// Admin Public Functions
// ===================================================================================================
//================================== Pausable =======================================/
function pause() external virtual {
require(owner() == _msgSender(), "Inventory: not the owner");
_pause();
}
function unpause() external virtual {
require(owner() == _msgSender(), "Inventory: not the owner");
_unpause();
}
//================================== ERC1155Inventory =======================================/
/**
* Creates a collection.
* @dev Reverts if `collectionId` does not represent a collection.
* @dev Reverts if `collectionId` has already been created.
* @dev Emits a {IERC1155Inventory-CollectionCreated} event.
* @param collectionId Identifier of the collection.
*/
function createCollection(uint256 collectionId) external onlyOwner {
_createCollection(collectionId);
}
//================================== ERC1155721InventoryMintable =======================================/
/**
* Unsafely mints a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256)}.
*/
function mint(address to, uint256 nftId) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_mint(to, nftId, "", false);
}
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256[])}.
*/
function batchMint(address to, uint256[] memory nftIds) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_batchMint(to, nftIds);
}
/**
* Safely mints a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,bytes)}.
*/
function safeMint(
address to,
uint256 nftId,
bytes memory data
) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_mint(to, nftId, data, true);
}
/**
* Safely mints some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}.
*/
function safeMint(
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_safeMint(to, id, value, data);
}
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeBatchMint(address,uint256[],uint256[],bytes)}.
*/
function safeBatchMint(
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_safeBatchMint(to, ids, values, data);
}
//================================== ERC721 =======================================/
function transferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
require(!paused(), "Inventory: paused");
super.transferFrom(from, to, nftId);
}
function batchTransferFrom(
address from,
address to,
uint256[] memory nftIds
) public virtual override {
require(!paused(), "Inventory: paused");
super.batchTransferFrom(from, to, nftIds);
}
function safeTransferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeTransferFrom(from, to, nftId);
}
function safeTransferFrom(
address from,
address to,
uint256 nftId,
bytes memory data
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeTransferFrom(from, to, nftId, data);
}
function batchBurnFrom(address from, uint256[] memory nftIds) public virtual override {
require(!paused(), "Inventory: paused");
super.batchBurnFrom(from, nftIds);
}
//================================== ERC1155 =======================================/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeTransferFrom(from, to, id, value, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeBatchTransferFrom(from, to, ids, values, data);
}
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
require(!paused(), "Inventory: paused");
super.burnFrom(from, id, value);
}
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
require(!paused(), "Inventory: paused");
super.batchBurnFrom(from, ids, values);
}
} | See {IERC1155MetadataURI-uri(uint256)}. | function uri(uint256 id) public view virtual override returns (string memory) {
return _uri(id);
}
| 2,505,877 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "hardhat/console.sol";
contract Presale is ReentrancyGuard, Ownable {
uint256 public constant DECIMALS = 18;
uint256 public constant DENOMINATOR = 10**DECIMALS;
uint256 public constant INITIAL_PRICE = (DENOMINATOR) / 7402; //Initial price 1 ETH == 7402 tokens
/**
* @dev price must be set with `DENOMINATOR` decimals
*/
uint256 public price = INITIAL_PRICE;
address payable public receiverOfEarnings;
IERC20Metadata public presaleToken;
uint8 internal tokenDecimals;
bool public paused;
event PriceChange(uint256 oldPrice, uint256 newPrice);
event BoughtWithBNB(uint256 amount);
/**
* @dev Throws is the presale is paused
*/
modifier notPaused() {
require(!paused, "Presale is paused");
_;
}
/**
* @dev Throws is presale is NOT paused
*/
modifier isPaused() {
require(paused, "Presale is not paused");
_;
}
/**
* @param _presaleToken adress of the token to be purchased through preslae
* @param _receiverOfEarnings address of the wallet to be allowed to withdraw the proceeds
*/
constructor(
address _presaleToken,
address payable _receiverOfEarnings
) {
require(
_receiverOfEarnings != address(0),
"Receiver wallet cannot be 0"
);
receiverOfEarnings = _receiverOfEarnings;
presaleToken = IERC20Metadata(_presaleToken);
tokenDecimals = presaleToken.decimals();
paused = true; //@dev start as paused
}
/**
* @notice Sets the address allowed to withdraw the proceeds from presale
* @param _receiverOfEarnings address of the reveiver
*/
function setReceiverOfEarnings(address payable _receiverOfEarnings)
external
onlyOwner
{
require(
_receiverOfEarnings != receiverOfEarnings,
"Receiver already configured"
);
require(_receiverOfEarnings != address(0), "Receiver cannot be 0");
receiverOfEarnings = _receiverOfEarnings;
}
/**
* @notice Sets new price for the presale token
* @param _price new price of the presale token - uses `DECIMALS` for precision
*/
function setPrice(uint256 _price) external onlyOwner {
require(_price != price, "New price cannot be same");
uint256 _oldPrice = price;
price = _price;
emit PriceChange(_oldPrice, _price);
}
/**
* @notice Releases presale tokens to the recipient
* @param _recipient recipient of the presale tokens
* @param _paidAmount amount paid by recipient
*/
function _releasePresaleTokens(
address _recipient,
uint256 _paidAmount
) internal {
uint256 tokensToReceive = calculateTokensToReceive(_paidAmount);
require(
tokensToReceive <= presaleToken.balanceOf(address(this)),
"Contract balance too low"
);
require(
presaleToken.transfer(_recipient, tokensToReceive),
"Token transfer failed"
);
}
receive() external payable {
buyTokensWithBNB();
}
/**
* @notice Allows purchase of presale tokens using BNB
*/
function buyTokensWithBNB()
public
payable
notPaused
nonReentrant
{
require(msg.value > 0, "No BNB sent");
_releasePresaleTokens(msg.sender, msg.value);
emit BoughtWithBNB(msg.value);
}
/**
* @notice Transfers collected funds to `receiverOfEarnings` address
*/
function withdraw() external {
require(
msg.sender == receiverOfEarnings,
"Sender not allowed to withdraw"
);
uint256 bnbBalance = address(this).balance;
if (bnbBalance > 0) {
payable(receiverOfEarnings).transfer(bnbBalance);
}
}
/**
* @notice Transfers all remaining `presaleToken` balance to owner when presale is over
*/
function rescuePresaleTokens() external onlyOwner isPaused {
uint256 balance = presaleToken.balanceOf(address(this));
require(balance > 0, "No tokens to rescue");
require(
presaleToken.transfer(owner(), balance),
"Token transfer failed"
);
}
/**
* @notice Calculates the amount of `presaleToken` based on the amount of `paidWithToken`
* @param _amount amount of `paidWithToken` used in purchase
*/
function calculateTokensToReceive(uint256 _amount)
public
view
returns (uint256)
{
uint256 amountToTransfer = (_amount * 10**tokenDecimals) / price;
return amountToTransfer;
}
/**
* @notice Pauses the presale
*/
function pause() external onlyOwner notPaused {
paused = true;
}
/**
* @notice Unpauses the presale
*/
function unpause() external onlyOwner isPaused {
paused = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// 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 (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;
}
} | Pauses the presale/ | function pause() external onlyOwner notPaused {
paused = true;
}
| 13,788,905 |
pragma solidity ^0.4.18;
import "installed_contracts/oraclize-api/contracts/usingOraclize.sol";
/**
@title Oracle - using Oraclize to make external API calls
@notice There are not tests for functions using Oracle such as getPollution() and __callback()
because these functions require an external call to Oraclize and cannot be tested with solidty tests.
@dev Currently the contract calls WolframAlpha for the current US pollution data
*/
contract Oracle is usingOraclize{
string public pollution;
bytes32 public oraclizeID;
/*** EVENTS ***/
event LogConstructorInitiated(string nextStep);
event LogPollutionUpdated(string unit);
event LogUpdate(string description);
/** @dev constructor emitting initiation event*/
constructor () public{
//During production the OAR is automatically fetched
emit LogConstructorInitiated("Constructor was initiated. Call 'getPullution()' to send the Oraclize Query.");
}
/** @dev pausable enables emergency stop */
function getPollution() public payable {
// get ID for debugging purposes
oraclizeID = oraclize_query("WolframAlpha", "greenhouse gas emissions United States");
}
/** @dev callback for Oraclize to return the queried data
@param _oraclizeID ID of the Oraclize query
@param result the result of the query
*/
function __callback(bytes32 _oraclizeID, string result) public{
//prevent anyone other than Oracle from calling the function
if (msg.sender != oraclize_cbAddress()) revert("function callner not from oraclize_cbAddress");
pollution = result;
emit LogPollutionUpdated(result);
}
function getBalance() public returns (uint _balance){
return address(this).balance;
}
} | pausable enables emergency stop / get ID for debugging purposes | function getPollution() public payable {
oraclizeID = oraclize_query("WolframAlpha", "greenhouse gas emissions United States");
}
@param result the result of the query
| 6,391,316 |
pragma solidity ^0.4.23;
import "./Ownable.sol";
import { MerkleProof } from "./MerkleProof.sol";
contract Checkpoint is Ownable {
address public owner;
uint256 public checkpointId = 0;
mapping(uint256 => uint256) public checkpoints;
event LogCheckpoint(uint256 indexed checkpointId);
// TODO: owner should be multisig of nodes
constructor(address _owner) public {
transferOwnership(_owner);
}
// TODO: pass sigs and check sigs of root provided
function checkpoint(uint256 root) public onlyOwner {
checkpoints[checkpointId] = root;
emit LogCheckpoint(checkpointId);
checkpointId++;
}
function verify(
bytes32[] proof,
bytes32 root,
bytes32 leaf
)
public
pure
returns (bool)
{
return MerkleProof.verify(proof, root, leaf);
}
}
| TODO: pass sigs and check sigs of root provided | function checkpoint(uint256 root) public onlyOwner {
checkpoints[checkpointId] = root;
emit LogCheckpoint(checkpointId);
checkpointId++;
}
| 12,748,329 |
./full_match/5/0x6cB5677a327d4D26876F8580FD08C679c95cD1F3/sources/src/token/ERC721/facets/minting/ERC721MintableRoleBased.sol | @inheritdoc IERC721MintableRoleBased/ | function mintByRole(address[] calldata tos, uint256[] calldata amounts) public virtual onlyRole(MINTER_ROLE) {
IERC721MintableExtension(address(this)).mintByFacet(tos, amounts);
}
| 1,853,808 |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// 'AGRI' - AgriChain Utility Token Contract
//
// Symbol : AGRI
// Name : AgriChain Utility Token
// Max Total supply : 1,000,000,000.000000000000000000 (1 billion)
// Decimals : 18
//
// Company : AgriChain Pty Ltd
// : https://agrichain.com
// Version : 2.0
// Author : Martin Halford <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa9bea58aabadb8a3a9a2aba3a4e4a9a5a7">[email protected]</a>>
// Published : 13 Aug 2018
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x > MAX_UINT256 - y) revert();
return x + y;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x < y) revert();
return x - y;
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) revert();
return x * y;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// Agri Token
// ----------------------------------------------------------------------------
contract AgriToken is ERC20Interface, Owned {
using SafeMath for uint;
uint256 constant public MAX_SUPPLY = 1000000000000000000000000000; // 1 billion Agri
string public symbol;
string public name;
uint8 public decimals;
uint256 _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// Flag to allow or disallow transfers
bool public isAllowingTransfers;
// List of admins who can mint, burn and allow transfers of tokens
mapping (address => bool) public administrators;
// modifier to check if transfers being allowed
modifier allowingTransfers() {
require(isAllowingTransfers);
_;
}
// modifier to check admin status
modifier onlyAdmin() {
require(administrators[msg.sender]);
_;
}
// This notifies clients about the amount burnt , only owner is able to burn tokens
event Burn(address indexed burner, uint256 value);
// This notifies clients about the transfers being allowed or disallowed
event AllowTransfers ();
event DisallowTransfers ();
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(uint initialTokenSupply) public {
symbol = "AGRI";
name = "AgriChain";
decimals = 18;
_totalSupply = initialTokenSupply * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public allowingTransfers returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public allowingTransfers returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Administrator can mint additional tokens
// Do ** NOT ** let totalSupply exceed MAX_SUPPLY
// ------------------------------------------------------------------------
function mintTokens(uint256 _value) public onlyAdmin {
require(_totalSupply.add(_value) <= MAX_SUPPLY);
balances[msg.sender] = balances[msg.sender].add(_value);
_totalSupply = _totalSupply.add(_value);
emit Transfer(0, msg.sender, _value);
}
// ------------------------------------------------------------------------
// Administrator can burn tokens
// ------------------------------------------------------------------------
function burn(uint256 _value) public onlyAdmin {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(burner, _value);
}
// ------------------------------------------------------------------------
// Administrator can allow transfer of tokens
// ------------------------------------------------------------------------
function allowTransfers() public onlyAdmin {
isAllowingTransfers = true;
emit AllowTransfers();
}
// ------------------------------------------------------------------------
// Administrator can disallow transfer of tokens
// ------------------------------------------------------------------------
function disallowTransfers() public onlyAdmin {
isAllowingTransfers = false;
emit DisallowTransfers();
}
// ------------------------------------------------------------------------
// Owner can add administrators of tokens
// ------------------------------------------------------------------------
function addAdministrator(address _admin) public onlyOwner {
administrators[_admin] = true;
}
// ------------------------------------------------------------------------
// Owner can remove administrators of tokens
// ------------------------------------------------------------------------
function removeAdministrator(address _admin) public onlyOwner {
administrators[_admin] = false;
}
} | ------------------------------------------------------------------------ Owner can add administrators of tokens ------------------------------------------------------------------------ | function addAdministrator(address _admin) public onlyOwner {
administrators[_admin] = true;
}
| 2,270,271 |
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @dev 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);
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @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 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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
interface LootInterface {
function ownerOf(uint256 tokenId) external view returns (address owner);
}
contract Loot is ERC721Enumerable, ReentrancyGuard, Ownable {
uint256 public publicPrice = 10000000000000000; //0.01 ETH
//Loot Contract
address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
LootInterface public lootContract = LootInterface(lootAddress);
string[] private adjectives = [
"Surprising",
"Predictable",
"Agreeable",
"Mysterious",
"Colossal",
"Great",
"Huge",
"Lazy",
"Miniature",
"Microscopic",
"Massive",
"Puny",
"Immense",
"Large",
"Little",
"Scrawny",
"Short",
"Small",
"Tiny",
"Gigantic",
"Mammoth",
"Gentle",
"Lively",
"Ambitious",
"Delightful",
"Eager",
"Happy",
"Jolly",
"Polite",
"Victorious",
"Witty",
"Wonderful",
"Zealous",
"Attractive",
"Dazzling",
"Magnificent",
"Plain",
"Scruffy",
"Unsightly",
"Legendary",
"Sneaky",
"Fit",
"Drab",
"Elegant",
"Glamorous",
"Truthful",
"Pitiful",
"Angry",
"Fierce",
"Embarrassed",
"Scary",
"Terrifying",
"Panicky",
"Thoughtless",
"Worried",
"Foolish",
"Frantic",
"Perfect",
"Timely",
"Dashing",
"Dangerous",
"Icy",
"Dull",
"Cloudy",
"Enchanting"
];
string[] private toots = [
"Butt ghost",
"Fart",
"Wind",
"Air biscuit",
"Bark",
"Blast",
"Bomber",
"Boom-boom",
"Bubbler",
"Burner",
"Butt Bazooka",
"Butt Bongo",
"Butt Sneeze",
"Butt Trumpet",
"Butt Tuba",
"Butt Yodeling",
"Cheek Squeak",
"Cheeser",
"Drifter",
"Fizzler",
"Flatus",
"Floater",
"Fluffy",
"Frump",
"Gas",
"Grunt",
"Gurgler",
"Hisser",
"Honker",
"Hot wind",
"Nasty cough",
"One-man salute",
"Bottom burp",
"Peter",
"Pewie",
"Poof",
"Pootsa",
"Pop tart",
"Power puff",
"Puffer",
"Putt-Putt",
"Quack",
"Quaker",
"Raspberry",
"Rattler",
"Rump Ripper",
"Rump Roar",
"Slider",
"Spitter",
"Squeaker",
"Steamer",
"Stinker",
"Stinky",
"Tootsie",
"Trouser Cough",
"Trouser Trumpet",
"Trunk Bunk",
"Turtle Burp",
"Tushy Tickler",
"Under Thunder",
"Wallop",
"Whiff",
"Whoopee",
"Whopper",
"Vapor Loaf"
];
string[] private suffixes = [
"of Might",
"of Tang",
"of Death",
"of Life",
"of Pollution",
"of Power",
"of Giants",
"of Titans",
"of Skill",
"of Perfection",
"of Brilliance",
"of Enlightenment",
"of Protection",
"of Anger",
"of Rage",
"of Fury",
"of Vitriol",
"of the Fox",
"of Detection",
"of Reflection",
"of the Twins",
"of the Smog",
"of the Dragon"
];
string[] private namePrefixes = [
"Agony", "Apocalypse", "Armageddon", "Beast", "Behemoth", "Blight", "Blood", "Bramble",
"Brimstone", "Brood", "Carrion", "Cataclysm", "Chimeric", "Corpse", "Corruption", "Damnation",
"Death", "Demon", "Dire", "Dragon", "Dread", "Doom", "Dusk", "Eagle", "Empyrean", "Fate", "Foe",
"Gale", "Ghoul", "Gloom", "Glyph", "Golem", "Grim", "Hate", "Havoc", "Honour", "Horror", "Hypnotic",
"Kraken", "Loath", "Maelstrom", "Mind", "Miracle", "Morbid", "Oblivion", "Onslaught", "Pain",
"Pandemonium", "Phoenix", "Plague", "Rage", "Rapture", "Rune", "Skull", "Sol", "Soul", "Sorrow",
"Spirit", "Storm", "Tempest", "Torment", "Vengeance", "Victory", "Viper", "Vortex", "Woe", "Wrath",
"Light's", "Shimmering"
];
string[] private nameSuffixes = [
"Bane",
"Root",
"Bite",
"Song",
"Roar",
"Grasp",
"Instrument",
"Glow",
"Bender",
"Shadow",
"Whisper",
"Shout",
"Growl",
"Tear",
"Peak",
"Form",
"Sun",
"Moon"
];
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function getToot(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "TOOT", toots);
}
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId))));
string memory output = sourceArray[rand % sourceArray.length];
output = string(abi.encodePacked(adjectives[rand % adjectives.length], " ", output));
uint256 greatness = rand % 21;
if (greatness > 14) {
output = string(abi.encodePacked(output, " ", suffixes[rand % suffixes.length]));
}
if (greatness >= 18) {
string[2] memory name;
name[0] = namePrefixes[rand % namePrefixes.length];
name[1] = nameSuffixes[rand % nameSuffixes.length];
if (greatness == 18) {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output));
} else {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1"));
}
}
return output;
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
string[17] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
parts[1] = getToot(tokenId);
parts[3] = '</text><text x="10" y="40" class="base">';
parts[4] = '</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Toot #', toString(tokenId), '", "description": "Toots are randomized adventurer farts generated and stored on chain. Smells, Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Toots in any way you want. Compatible with Loot (for Adventurers)", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
function mint(uint256 tokenId) public payable{
require(tokenId > 8000 && tokenId < 16000, "Token ID invalid");
require(publicPrice <= msg.value, "Ether value sent is not correct");
_safeMint(_msgSender(), tokenId);
}
function multiMint(uint256[] memory tokenIds) public payable nonReentrant {
require((publicPrice * tokenIds.length) <= msg.value, "Ether value sent is not correct");
for (uint256 i = 0; i < tokenIds.length; i++) {
require(tokenIds[i] > 8000 && tokenIds[i] < 16000, "Token ID invalid");
_safeMint(msg.sender, tokenIds[i]);
}
}
function mintWithLoot(uint256 lootId) public payable nonReentrant {
require(lootId > 0 && lootId <= 8000, "Token ID invalid");
require(lootContract.ownerOf(lootId) == msg.sender, "Not the owner of this loot");
_safeMint(_msgSender(), lootId);
}
function multiMintWithLoot(uint256[] memory lootIds) public payable nonReentrant {
for (uint256 i = 0; i < lootIds.length; i++) {
require(lootContract.ownerOf(lootIds[i]) == msg.sender, "Not the owner of this loot");
_safeMint(_msgSender(), lootIds[i]);
}
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function withdrawAll() public payable onlyOwner {
require(payable(_msgSender()).send(address(this).balance));
}
constructor() ERC721("Toot", "TOOT") Ownable() {}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} | Private function to add a token to this extension's ownership-tracking data structures. to address representing the new owner of the given token ID tokenId uint256 ID of the token to be added to the tokens list of the given address/ | function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
| 1,635,148 |
./full_match/3/0x41e41df9D882D78C8Bc35cf56eD0337a55C8B082/sources/Dapp1/TokenTest.sol | You must not set element 0xffffffff to true | function ERC165MappingImplementation() internal {
supportedInterfaces[this.supportsInterface.selector] = true;
}
| 8,260,012 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV15Interface {
event Trade(
address account,
address suppliedAsset,
address receivedAsset,
address retainedAsset,
uint256 suppliedAmount,
uint256 recievedAmount,
uint256 retainedAmount
);
event RoleModified(Role indexed role, address account);
event RolePaused(Role indexed role);
event RoleUnpaused(Role indexed role);
event EtherReceived(address sender, uint256 amount);
event GasReserveRefilled(uint256 etherAmount);
event Withdrawal(
string indexed asset, address indexed primaryRecipient, uint256 amount
);
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER, // 4
GAS_RESERVE_REFILLER // 5
}
enum TradeType {
DAI_TO_TOKEN,
DAI_TO_ETH,
ETH_TO_DAI,
TOKEN_TO_DAI,
ETH_TO_TOKEN,
TOKEN_TO_ETH,
TOKEN_TO_TOKEN
}
struct RoleStatus {
address account;
bool paused;
}
function tradeDaiForEtherV2(
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed);
function tradeEtherForDaiV2(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function tradeEtherForDaiAndMintDDai(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold);
function tradeDDaiForToken(
address token,
uint256 daiEquivalentAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed);
function tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought);
function tradeTokenForDaiAndMintDDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought);
function tradeEtherForToken(
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold);
function tradeEtherForTokenUsingEtherizer(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold);
function tradeTokenForToken(
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold);
function tradeTokenForTokenUsingReserves(
ERC20Interface tokenProvidedFromReserves,
address tokenReceived,
uint256 tokenProvidedAmountFromReserves,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold);
function tradeDaiForEtherUsingReservesV2(
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function tradeEtherForDaiUsingReservesAndMintDDaiV2(
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeDaiForTokenUsingReserves(
address token,
uint256 daiAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold);
function tradeTokenForDaiUsingReservesAndMintDDai(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeTokenForEtherUsingReserves(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought);
function tradeEtherForTokenUsingReserves(
address token,
uint256 etherAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold);
function finalizeEtherDeposit(
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function mint(uint256 daiAmount) external returns (uint256 dDaiMinted);
function redeem(uint256 dDaiAmount) external returns (uint256 daiReceived);
function redeemUnderlying(
uint256 daiAmount
) external returns (uint256 dDaiSupplied);
function tradeDDaiForUSDC(
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function tradeUSDCForDDai(
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function refillGasReserve(uint256 etherAmount) external;
function withdrawUSDC(address recipient, uint256 usdcAmount) external;
function withdrawDai(address recipient, uint256 daiAmount) external;
function withdrawDharmaDai(address recipient, uint256 dDaiAmount) external;
function withdrawUSDCToPrimaryRecipient(uint256 usdcAmount) external;
function withdrawDaiToPrimaryRecipient(uint256 usdcAmount) external;
function withdrawEtherToPrimaryRecipient(uint256 etherAmount) external;
function withdrawEther(
address payable recipient, uint256 etherAmount
) external;
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function callAny(
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function setDaiLimit(uint256 daiAmount) external;
function setEtherLimit(uint256 daiAmount) external;
function setPrimaryUSDCRecipient(address recipient) external;
function setPrimaryDaiRecipient(address recipient) external;
function setPrimaryEtherRecipient(address recipient) external;
function setRole(Role role, address account) external;
function removeRole(Role role) external;
function pause(Role role) external;
function unpause(Role role) external;
function isPaused(Role role) external view returns (bool paused);
function isRole(Role role) external view returns (bool hasRole);
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function getDepositManager() external view returns (address depositManager);
function getAdjuster() external view returns (address adjuster);
function getReserveTrader() external view returns (address reserveTrader);
function getWithdrawalManager() external view returns (
address withdrawalManager
);
function getPauser() external view returns (address pauser);
function getGasReserveRefiller() external view returns (
address gasReserveRefiller
);
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function getDaiLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
);
function getEtherLimit() external view returns (uint256 etherAmount);
function getPrimaryUSDCRecipient() external view returns (
address recipient
);
function getPrimaryDaiRecipient() external view returns (
address recipient
);
function getPrimaryEtherRecipient() external view returns (
address recipient
);
function getImplementation() external view returns (address implementation);
function getInstance() external pure returns (address instance);
function getVersion() external view returns (uint256 version);
}
interface ERC20Interface {
function balanceOf(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function allowance(address, address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
interface DTokenInterface {
function redeem(
uint256 dTokensToBurn
) external returns (uint256 underlyingReceived);
function balanceOf(address) external view returns (uint256);
function balanceOfUnderlying(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function exchangeRateCurrent() external view returns (uint256);
}
interface DharmaDaiExchangerInterface {
function mintTo(
address account, uint256 daiToSupply
) external returns (uint256 dDaiMinted);
function redeemUnderlyingTo(
address account, uint256 daiToReceive
) external returns (uint256 dDaiBurned);
}
interface TradeHelperInterface {
function tradeUSDCForDDai(
uint256 amountUSDC,
uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function tradeDDaiForUSDC(
uint256 amountDai,
uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function getExpectedDai(uint256 usdc) external view returns (uint256 dai);
function getExpectedUSDC(uint256 dai) external view returns (uint256 usdc);
}
interface UniswapV2Interface {
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function settleEther() external;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*
* In order to transfer ownership, a recipient must be specified, at which point
* the specified recipient can call `acceptOwnership` and take ownership.
*/
contract TwoStepOwnable {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
/**
* @dev Allows a new account (`newOwner`) to accept ownership.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
/**
* @dev Cancel a transfer of ownership to a new account.
* Can only be called by the current owner.
*/
function cancelOwnershipTransfer() external onlyOwner {
delete _newPotentialOwner;
}
/**
* @dev Transfers ownership of the contract to the caller.
* Can only be called by a new potential owner set by the current owner.
*/
function acceptOwnership() external {
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OwnershipTransferred(_owner, msg.sender);
_owner = msg.sender;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() external view returns (address) {
return _owner;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
/**
* @title DharmaTradeReserveV15ImplementationStaging
* @author 0age
* @notice This contract manages Dharma's reserves. It designates a collection
* of "roles" - these are dedicated accounts that can be modified by the owner,
* and that can trigger specific functionality on the reserve. These roles are:
* - depositManager (0): initiates Eth / token transfers to smart wallets
* - adjuster (1): mints / redeems Dai, and swaps USDC, for dDai
* - withdrawalManager (2): initiates transfers to recipients set by the owner
* - reserveTrader (3): initiates trades using funds held in reserve
* - pauser (4): pauses any role (only the owner is then able to unpause it)
* - gasReserveRefiller (5): transfers Ether to the Dharma Gas Reserve
*
* When finalizing deposits, the deposit manager must adhere to two constraints:
* - it must provide "proof" that the recipient is a smart wallet by including
* the initial user signing key used to derive the smart wallet address
* - it must not attempt to transfer more Eth, Dai, or the Dai-equivalent
* value of Dharma Dai, than the current "limit" set by the owner.
*
* Note that "proofs" can be validated via `isSmartWallet`.
*/
contract DharmaTradeReserveV15ImplementationStaging is DharmaTradeReserveV15Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable Dai transfer size for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable Ether transfer size for the deposit manager.
uint256 private _etherLimit;
bool private _unused; // unused, don't change storage layout
// Maintain a "primary recipient" where withdrawal manager can transfer Ether.
address private _primaryEtherRecipient;
uint256 private constant _VERSION = 1015;
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _USDC = ERC20Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _ETHERIZER = ERC20Interface(
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430
);
DharmaDaiExchangerInterface internal constant _DDAI_EXCHANGER = (
DharmaDaiExchangerInterface(
0x83E02F0b169be417C38d1216fc2a5134C48Af44a
)
);
TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface(
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV2Interface internal constant _UNISWAP_ROUTER = UniswapV2Interface(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _ETH_RECEIVER = (
EtherReceiverInterface(
0xaf84687D21736F5E06f738c6F065e88890465E7c
)
);
address internal constant _WETH = address(
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
address internal constant _GAS_RESERVE = address(
0x09cd826D4ABA4088E1381A1957962C946520952d // staging version
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _CREATE2_HEADER = bytes21(
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000";
bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28(
0x00000000000000000000000000000000000000000000000000000000
);
string internal constant _TRANSFER_SIZE_EXCEEDED = string(
"Transfer size exceeds limit."
);
function initialize() external onlyOwner {
require(_DAI.approve(address(_DDAI_EXCHANGER), uint256(-1)));
require(_DDAI.approve(address(_DDAI_EXCHANGER), uint256(-1)));
}
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit EtherReceived(msg.sender, msg.value);
}
/**
* @notice Pull in `daiAmount` Dai from the caller, trade it for Ether using
* UniswapV2, and return `quotedEtherAmount` Ether to the caller.
* @param daiAmount uint256 The Dai amount to supply when trading for Ether.
* @param quotedEtherAmount uint256 The amount of Ether to return to caller.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai sold as part of the trade.
*/
function tradeDaiForEtherV2(
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_transferInToken(_DAI, msg.sender, daiAmount);
// Trade Dai for Ether.
totalDaiSold = _tradeDaiForEther(
daiAmount, quotedEtherAmount, deadline, false
);
}
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
// Transfer in sufficient dDai and use it to mint Dai.
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
// Trade minted Dai for Ether.
totalDaiSold = _tradeDaiForEther(
daiEquivalentAmount, quotedEtherAmount, deadline, false
);
}
function tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought) {
// Transfer the tokens from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade tokens for Ether.
totalEtherBought = _tradeTokenForEther(
token, tokenAmount, quotedEtherAmount, deadline, false
);
// Transfer the quoted Ether amount to the caller.
_transferEther(msg.sender, quotedEtherAmount);
}
function tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_transferInToken(_DAI, msg.sender, daiAmount);
// Trade Dai for specified token.
totalDaiSold = _tradeDaiForToken(
token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false
);
}
function tradeDDaiForToken(
address token,
uint256 daiEquivalentAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
// Transfer in sufficient dDai and use it to mint Dai.
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
// Trade minted Dai for specified token.
totalDaiSold = _tradeDaiForToken(
token,
daiEquivalentAmount,
quotedTokenAmount,
deadline,
routeThroughEther,
false
);
}
/**
* @notice Using `daiAmountFromReserves` Dai (note that dDai will be redeemed
* if necessary), trade for Ether using UniswapV2. Only the owner or the trade
* reserve role can call this function. Note that Dharma Dai will be redeemed
* to cover the Dai if there is not enough currently in the contract.
* @param daiAmountFromReserves the amount of Dai to take from reserves.
* @param quotedEtherAmount uint256 The Ether amount requested in the trade.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Ether bought as part of the trade.
*/
function tradeDaiForEtherUsingReservesV2(
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
_redeemDDaiIfNecessary(daiAmountFromReserves);
// Trade Dai for Ether using reserves.
totalDaiSold = _tradeDaiForEther(
daiAmountFromReserves, quotedEtherAmount, deadline, true
);
}
function tradeTokenForEtherUsingReserves(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedEtherAmount,
uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalEtherBought
) {
// Trade tokens for Ether using reserves.
totalEtherBought = _tradeTokenForEther(
token, tokenAmountFromReserves, quotedEtherAmount, deadline, true
);
}
/**
* @notice Accept `msg.value` Ether from the caller, trade it for Dai using
* UniswapV2, and return `quotedDaiAmount` Dai to the caller.
* @param quotedDaiAmount uint256 The amount of Dai to return to the caller.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai bought as part of the trade.
*/
function tradeEtherForDaiV2(
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade Ether for Dai.
totalDaiBought = _tradeEtherForDai(
msg.value, quotedDaiAmount, deadline, false
);
// Transfer the Dai to the caller and revert on failure.
_transferToken(_DAI, msg.sender, quotedDaiAmount);
}
function tradeEtherForDaiAndMintDDai(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought, uint256 totalDDaiMinted) {
// Trade Ether for Dai.
totalDaiBought = _tradeEtherForDai(
msg.value, quotedDaiAmount, deadline, false
);
// Mint dDai to caller using quoted amount (retained amount stays in Dai).
totalDDaiMinted = _mintDDai(quotedDaiAmount, true);
}
function tradeEtherForToken(
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold) {
// Trade Ether for the specified token.
totalEtherSold = _tradeEtherForToken(
token, msg.value, quotedTokenAmount, deadline, false
);
}
function tradeEtherForTokenUsingEtherizer(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold) {
// Transfer the Ether from the caller and revert on failure.
_transferInToken(_ETHERIZER, msg.sender, etherAmount);
// Trade Ether for the specified token.
totalEtherSold = _tradeEtherForToken(
token, etherAmount, quotedTokenAmount, deadline, false
);
}
function tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade the token for Dai.
totalDaiBought = _tradeTokenForDai(
token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false
);
// Transfer the quoted Dai amount to the caller and revert on failure.
_transferToken(_DAI, msg.sender, quotedDaiAmount);
}
function tradeTokenForDaiAndMintDDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted) {
// Transfer the token from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade the token for Dai.
totalDaiBought = _tradeTokenForDai(
token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false
);
// Mint dDai to caller using quoted amount (retained amount stays in Dai).
totalDDaiMinted = _mintDDai(quotedDaiAmount, true);
}
function tradeTokenForToken(
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold) {
// Transfer the token from the caller and revert on failure.
_transferInToken(tokenProvided, msg.sender, tokenProvidedAmount);
totalTokensSold = _tradeTokenForToken(
msg.sender,
tokenProvided,
tokenReceived,
tokenProvidedAmount,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
);
}
function tradeTokenForTokenUsingReserves(
ERC20Interface tokenProvidedFromReserves,
address tokenReceived,
uint256 tokenProvidedAmountFromReserves,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalTokensSold
) {
totalTokensSold = _tradeTokenForToken(
address(this),
tokenProvidedFromReserves,
tokenReceived,
tokenProvidedAmountFromReserves,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
);
}
/**
* @notice Using `etherAmountFromReserves`, trade for Dai using UniswapV2,
* and use that Dai to mint Dharma Dai.
* Only the owner or the trade reserve role can call this function.
* @param etherAmountFromReserves the amount of Ether to take from reserves
* and add to the provided amount.
* @param quotedDaiAmount uint256 The amount of Dai requested in the trade.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai bought as part of the trade.
*/
function tradeEtherForDaiUsingReservesAndMintDDaiV2(
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade Ether for Dai using reserves.
totalDaiBought = _tradeEtherForDai(
etherAmountFromReserves, quotedDaiAmount, deadline, true
);
// Mint dDai using the received Dai.
totalDDaiMinted = _mintDDai(totalDaiBought, false);
}
function tradeEtherForTokenUsingReserves(
address token,
uint256 etherAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) {
// Trade Ether for token using reserves.
totalEtherSold = _tradeEtherForToken(
token, etherAmountFromReserves, quotedTokenAmount, deadline, true
);
}
function tradeDaiForTokenUsingReserves(
address token,
uint256 daiAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
_redeemDDaiIfNecessary(daiAmountFromReserves);
// Trade Dai for token using reserves.
totalDaiSold = _tradeDaiForToken(
token,
daiAmountFromReserves,
quotedTokenAmount,
deadline,
routeThroughEther,
true
);
}
function tradeTokenForDaiUsingReservesAndMintDDai(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the token for Dai using reserves.
totalDaiBought = _tradeTokenForDai(
token,
tokenAmountFromReserves,
quotedDaiAmount,
deadline,
routeThroughEther,
true
);
// Mint dDai using the received Dai.
totalDDaiMinted = _mintDDai(totalDaiBought, false);
}
/**
* @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial
* user signing key `initialUserSigningKey` as proof that the specified smart
* wallet is indeed a Dharma Smart Wallet - this assumes that the address is
* derived and deployed using the Dharma Smart Wallet Factory V1. In addition,
* the specified amount must be less than the configured limit amount. Only
* the owner or the designated deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param daiAmount uint256 The amount of Dai to transfer - this must be less
* than the current limit.
*/
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the Dai to the specified smart wallet.
_transferToken(_DAI, smartWallet, daiAmount);
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Dai equivalent value of the specified dDai amount must
* be less than the configured limit amount. Only the owner or the designated
* deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai
* equivalent amount must be less than the current limit.
*/
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Get the current dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Invalid dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the dDai to the specified smart wallet.
_transferToken(ERC20Interface(address(_DDAI)), smartWallet, dDaiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Ether amount must be less than the configured limit
* amount. Only the owner or the designated deposit manager role may call this
* function.
* @param smartWallet address The smart wallet to transfer Ether to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param etherAmount uint256 The amount of Ether to transfer - this amount
* must be less than the current limit.
*/
function finalizeEtherDeposit(
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the Ether to the specified smart wallet.
_transferEther(smartWallet, etherAmount);
}
/**
* @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to supply when minting Dharma
* Dai.
* @return The amount of Dharma Dai minted.
*/
function mint(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _mintDDai(daiAmount, false);
}
/**
* @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the
* designated adjuster role may call this function.
* @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming
* for Dai.
* @return The amount of Dai received.
*/
function redeem(
uint256 dDaiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _DDAI.redeem(dDaiAmount);
}
/**
* @notice Receive `daiAmount` Dai in exchange for Dharma Dai. Only the owner
* or the designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to receive when redeeming
* Dharma Dai.
* @return The amount of Dharma Dai supplied.
*/
function redeemUnderlying(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiSupplied) {
// Redeem the specified amount of dDai for Dai.
dDaiSupplied = _DDAI_EXCHANGER.redeemUnderlyingTo(address(this), daiAmount);
}
/**
* @notice trade `usdcAmount` USDC for Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param usdcAmount uint256 The amount of USDC to supply when trading for
* Dharma Dai.
* @param quotedDaiEquivalentAmount uint256 The expected DAI equivalent value
* of the received dDai - this value is returned from the `getAndExpectedDai`
* view function on the trade helper.
* @return The amount of dDai received.
*/
function tradeUSDCForDDai(
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai(
usdcAmount, quotedDaiEquivalentAmount
);
}
/**
* @notice tradeDDaiForUSDC `daiEquivalentAmount` Dai amount to trade in
* Dharma Dai for USDC. Only the owner or the designated adjuster role may
* call this function.
* @param daiEquivalentAmount uint256 The Dai equivalent amount to supply in
* Dharma Dai when trading for USDC.
* @param quotedUSDCAmount uint256 The expected USDC received in exchange for
* dDai - this value is returned from the `getExpectedUSDC` view function on
* the trade helper.
* @return The amount of USDC received.
*/
function tradeDDaiForUSDC(
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _TRADE_HELPER.tradeDDaiForUSDC(
daiEquivalentAmount, quotedUSDCAmount
);
}
function refillGasReserve(
uint256 etherAmount
) external onlyOwnerOr(Role.GAS_RESERVE_REFILLER) {
// Transfer the Ether to the gas reserve.
_transferEther(_GAS_RESERVE, etherAmount);
emit GasReserveRefilled(etherAmount);
}
/**
* @notice Transfer `usdcAmount` USDC to the current primary recipient set by
* the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param usdcAmount uint256 The amount of USDC to transfer to the primary
* recipient.
*/
function withdrawUSDCToPrimaryRecipient(
uint256 usdcAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "USDC", usdcAmount
);
// Transfer the supplied USDC amount to the primary recipient.
_transferToken(_USDC, primaryRecipient, usdcAmount);
}
/**
* @notice Transfer `daiAmount` Dai to the current primary recipient set by
* the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param daiAmount uint256 The amount of Dai to transfer to the primary
* recipient.
*/
function withdrawDaiToPrimaryRecipient(
uint256 daiAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "Dai", daiAmount
);
// Transfer the supplied Dai amount to the primary recipient.
_transferToken(_DAI, primaryRecipient, daiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to the current primary recipient set
* by the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param etherAmount uint256 The amount of Ether to transfer to the primary
* recipient.
*/
function withdrawEtherToPrimaryRecipient(
uint256 etherAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryEtherRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "Ether", etherAmount
);
// Transfer the supplied Ether amount to the primary recipient.
_transferEther(primaryRecipient, etherAmount);
}
/**
* @notice Transfer `usdcAmount` USDC to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer USDC to.
* @param usdcAmount uint256 The amount of USDC to transfer.
*/
function withdrawUSDC(
address recipient, uint256 usdcAmount
) external onlyOwner {
// Transfer the USDC to the specified recipient.
_transferToken(_USDC, recipient, usdcAmount);
}
/**
* @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer Dai to.
* @param daiAmount uint256 The amount of Dai to transfer.
*/
function withdrawDai(
address recipient, uint256 daiAmount
) external onlyOwner {
// Transfer the Dai to the specified recipient.
_transferToken(_DAI, recipient, daiAmount);
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Dharma Dai to.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer.
*/
function withdrawDharmaDai(
address recipient, uint256 dDaiAmount
) external onlyOwner {
// Transfer the dDai to the specified recipient.
_transferToken(ERC20Interface(address(_DDAI)), recipient, dDaiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Ether to.
* @param etherAmount uint256 The amount of Ether to transfer.
*/
function withdrawEther(
address payable recipient, uint256 etherAmount
) external onlyOwner {
// Transfer the Ether to the specified recipient.
_transferEther(recipient, etherAmount);
}
/**
* @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the
* owner may call this function.
* @param token ERC20Interface The ERC20 token to transfer.
* @param recipient address The account to transfer the tokens to.
* @param amount uint256 The amount of tokens to transfer.
* @return A boolean to indicate if the transfer was successful - note that
* unsuccessful ERC20 transfers will usually revert.
*/
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external onlyOwner returns (bool success) {
// Transfer the token to the specified recipient.
success = token.transfer(recipient, amount);
}
/**
* @notice Call account `target`, supplying value `amount` and data `data`.
* Only the owner may call this function.
* @param target address The account to call.
* @param amount uint256 The amount of ether to include as an endowment.
* @param data bytes The data to include along with the call.
* @return A boolean to indicate if the call was successful, as well as the
* returned data or revert reason.
*/
function callAny(
address payable target, uint256 amount, bytes calldata data
) external onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
/**
* @notice Set `daiAmount` as the new limit on size of finalized deposits.
* Only the owner may call this function.
* @param daiAmount uint256 The new limit on the size of finalized deposits.
*/
function setDaiLimit(uint256 daiAmount) external onlyOwner {
// Set the new limit.
_daiLimit = daiAmount;
}
/**
* @notice Set `etherAmount` as the new limit on size of finalized deposits.
* Only the owner may call this function.
* @param etherAmount uint256 The new limit on the size of finalized deposits.
*/
function setEtherLimit(uint256 etherAmount) external onlyOwner {
// Set the new limit.
_etherLimit = etherAmount;
}
/**
* @notice Set `recipient` as the new primary recipient for USDC withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryUSDCRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
/**
* @notice Set `recipient` as the new primary recipient for Dai withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryDaiRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
/**
* @notice Set `recipient` as the new primary recipient for Ether withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryEtherRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryEtherRecipient = recipient;
}
/**
* @notice Pause a currently unpaused role and emit a `RolePaused` event. Only
* the owner or the designated pauser may call this function. Also, bear in
* mind that only the owner may unpause a role once paused.
* @param role The role to pause.
*/
function pause(Role role) external onlyOwnerOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
/**
* @notice Unpause a currently paused role and emit a `RoleUnpaused` event.
* Only the owner may call this function.
* @param role The role to pause.
*/
function unpause(Role role) external onlyOwner {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role is already unpaused.");
storedRoleStatus.paused = false;
emit RoleUnpaused(role);
}
/**
* @notice Set a new account on a given role and emit a `RoleModified` event
* if the role holder has changed. Only the owner may call this function.
* @param role The role that the account will be set for.
* @param account The account to set as the designated role bearer.
*/
function setRole(Role role, address account) external onlyOwner {
require(account != address(0), "Must supply an account.");
_setRole(role, account);
}
/**
* @notice Remove any current role bearer for a given role and emit a
* `RoleModified` event if a role holder was previously set. Only the owner
* may call this function.
* @param role The role that the account will be removed from.
*/
function removeRole(Role role) external onlyOwner {
_setRole(role, address(0));
}
/**
* @notice External view function to check whether or not the functionality
* associated with a given role is currently paused or not. The owner or the
* pauser may pause any given role (including the pauser itself), but only the
* owner may unpause functionality. Additionally, the owner may call paused
* functions directly.
* @param role The role to check the pause status on.
* @return A boolean to indicate if the functionality associated with the role
* in question is currently paused.
*/
function isPaused(Role role) external view returns (bool paused) {
paused = _isPaused(role);
}
/**
* @notice External view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return A boolean indicating if the caller has the specified role.
*/
function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
/**
* @notice External view function to check whether a "proof" that a given
* smart wallet is actually a Dharma Smart Wallet, based on the initial user
* signing key, is valid or not. This proof only works when the Dharma Smart
* Wallet in question is derived using V1 of the Dharma Smart Wallet Factory.
* @param smartWallet address The smart wallet to check.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @return A boolean indicating if the specified smart wallet account is
* indeed a smart wallet based on the specified initial user signing key.
*/
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey);
}
/**
* @notice External view function to check the account currently holding the
* deposit manager role. The deposit manager can process standard deposit
* finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but
* must prove that the recipient is a Dharma Smart Wallet and adhere to the
* current deposit size limit.
* @return The address of the current deposit manager, or the null address if
* none is set.
*/
function getDepositManager() external view returns (address depositManager) {
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and
* vice-versa via minting or redeeming.
* @return The address of the current adjuster, or the null address if none is
* set.
*/
function getAdjuster() external view returns (address adjuster) {
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
/**
* @notice External view function to check the account currently holding the
* reserve trader role. The reserve trader can trigger trades that utilize
* reserves in addition to supplied funds, if any.
* @return The address of the current reserve trader, or the null address if
* none is set.
*/
function getReserveTrader() external view returns (address reserveTrader) {
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
/**
* @notice External view function to check the account currently holding the
* withdrawal manager role. The withdrawal manager can transfer USDC, Dai, and
* Ether to their respective "primary recipient" accounts set by the owner.
* @return The address of the current withdrawal manager, or the null address
* if none is set.
*/
function getWithdrawalManager() external view returns (
address withdrawalManager
) {
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* pauser role. The pauser can pause any role from taking its standard action,
* though the owner will still be able to call the associated function in the
* interim and is the only entity able to unpause the given role once paused.
* @return The address of the current pauser, or the null address if none is
* set.
*/
function getPauser() external view returns (address pauser) {
pauser = _roles[uint256(Role.PAUSER)].account;
}
function getGasReserveRefiller() external view returns (
address gasReserveRefiller
) {
gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account;
}
/**
* @notice External view function to check the current reserves held by this
* contract.
* @return The Dai and Dharma Dai reserves held by this contract, as well as
* the Dai-equivalent value of the Dharma Dai reserves.
*/
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _DAI.balanceOf(address(this));
dDai = _DDAI.balanceOf(address(this));
dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this));
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing deposits, expressed in Dai
* and in Dharma Dai.
* @return The Dai and Dharma Dai limit on deposit finalization amount.
*/
function getDaiLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent());
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing Ether deposits.
* @return The Ether limit on deposit finalization amount.
*/
function getEtherLimit() external view returns (uint256 etherAmount) {
etherAmount = _etherLimit;
}
/**
* @notice External view function to check the address of the current
* primary recipient for USDC.
* @return The primary recipient for USDC.
*/
function getPrimaryUSDCRecipient() external view returns (
address recipient
) {
recipient = _primaryUSDCRecipient;
}
/**
* @notice External view function to check the address of the current
* primary recipient for Dai.
* @return The primary recipient for Dai.
*/
function getPrimaryDaiRecipient() external view returns (
address recipient
) {
recipient = _primaryDaiRecipient;
}
/**
* @notice External view function to check the address of the current
* primary recipient for Ether.
* @return The primary recipient for Ether.
*/
function getPrimaryEtherRecipient() external view returns (
address recipient
) {
recipient = _primaryEtherRecipient;
}
/**
* @notice External view function to check the current implementation
* of this contract (i.e. the "logic" for the contract).
* @return The current implementation for this contract.
*/
function getImplementation() external view returns (
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
/**
* @notice External pure function to get the address of the actual
* contract instance (i.e. the "storage" foor this contract).
* @return The address of this contract instance.
*/
function getInstance() external pure returns (address instance) {
instance = address(0x2040F2f2bB228927235Dc24C33e99E3A0a7922c1);
}
function getVersion() external view returns (uint256 version) {
version = _VERSION;
}
function _grantUniswapRouterApprovalIfNecessary(
ERC20Interface token, uint256 amount
) internal {
if (token.allowance(address(this), address(_UNISWAP_ROUTER)) < amount) {
// Try removing router approval first as a workaround for unusual tokens.
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), uint256(0)
)
);
// Approve Uniswap router to transfer tokens on behalf of this contract.
(success, data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), uint256(-1)
)
);
if (!success) {
// Some janky tokens only allow setting approval up to current balance.
(success, data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), amount
)
);
}
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Uniswap router token approval failed."
);
}
}
function _tradeEtherForDai(
uint256 etherAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalDaiBought) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(_DAI), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactETHForTokens.value(etherAmount)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_DAI,
address(0),
etherAmount,
quotedDaiAmount,
totalDaiBought.sub(quotedDaiAmount)
);
}
function _tradeDaiForEther(
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalDaiSold) {
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(_DAI), _WETH, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to correct recipient).
amounts = _UNISWAP_ROUTER.swapTokensForExactETH(
quotedEtherAmount,
daiAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalDaiSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.DAI_TO_ETH,
address(0),
daiAmount,
quotedEtherAmount,
daiAmount.sub(totalDaiSold)
);
}
function _tradeEtherForToken(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(token), false
);
// Trade Ether for the quoted token amount and send to correct recipient.
amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)(
quotedTokenAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalEtherSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_TOKEN,
address(token),
etherAmount,
quotedTokenAmount,
etherAmount.sub(totalEtherSold)
);
}
function _tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(token, tokenAmount);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(token), _WETH, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForETH(
tokenAmount, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
_fireTradeEvent(
fromReserves,
TradeType.TOKEN_TO_ETH,
address(token),
tokenAmount,
quotedEtherAmount,
totalEtherBought.sub(quotedEtherAmount)
);
}
function _tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther,
bool fromReserves
) internal returns (uint256 totalDaiSold) {
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(_DAI), address(token), routeThroughEther
);
// Trade Dai for quoted token amount and send to correct recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenAmount,
daiAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalDaiSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.DAI_TO_TOKEN,
address(token),
daiAmount,
quotedTokenAmount,
daiAmount.sub(totalDaiSold)
);
}
function _tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther,
bool fromReserves
) internal returns (uint256 totalDaiBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(token, tokenAmount);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(token), address(_DAI), routeThroughEther
);
// Trade Dai for the quoted token amount on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForTokens(
tokenAmount, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[path.length - 1];
_fireTradeEvent(
fromReserves,
TradeType.TOKEN_TO_DAI,
address(token),
tokenAmount,
quotedDaiAmount,
totalDaiBought.sub(quotedDaiAmount)
);
}
function _tradeTokenForToken(
address recipient,
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) internal returns (uint256 totalTokensSold) {
uint256 retainedAmount;
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(tokenProvided, tokenProvidedAmount);
if (routeThroughEther == false) {
// Establish direct path between tokens.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), tokenReceived, false
);
// Trade for the quoted token amount on Uniswap and send to recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenReceivedAmount,
tokenProvidedAmount,
path,
recipient,
deadline
);
totalTokensSold = amounts[0];
retainedAmount = tokenProvidedAmount.sub(totalTokensSold);
} else {
// Establish path between provided token and WETH.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), _WETH, false
);
// Trade all provided tokens for WETH on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForTokens(
tokenProvidedAmount, 0, path, address(this), deadline
);
retainedAmount = amounts[1];
// Establish path between WETH and received token.
(path, amounts) = _createPathAndAmounts(
_WETH, tokenReceived, false
);
// Trade bought WETH for received token on Uniswap and send to recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline
);
totalTokensSold = amounts[0];
retainedAmount = retainedAmount.sub(totalTokensSold);
}
emit Trade(
recipient,
address(tokenProvided),
tokenReceived,
routeThroughEther ? _WETH : address(tokenProvided),
tokenProvidedAmount,
quotedTokenReceivedAmount,
retainedAmount
);
}
/**
* @notice Internal function to set a new account on a given role and emit a
* `RoleModified` event if the role holder has changed.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
function _fireTradeEvent(
bool fromReserves,
TradeType tradeType,
address token,
uint256 suppliedAmount,
uint256 receivedAmount,
uint256 retainedAmount
) internal {
uint256 t = uint256(tradeType);
emit Trade(
fromReserves ? address(this) : msg.sender,
t < 2 ? address(_DAI) : (t % 2 == 0 ? address(0) : token),
(t > 1 && t < 4) ? address(_DAI) : (t % 2 == 0 ? token : address(0)),
t < 4 ? address(_DAI) : address(0),
suppliedAmount,
receivedAmount,
retainedAmount
);
}
/**
* @notice Internal view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return A boolean indicating if the caller has the specified role.
*/
function _isRole(Role role) internal view returns (bool hasRole) {
hasRole = msg.sender == _roles[uint256(role)].account;
}
/**
* @notice Internal view function to check whether the given role is paused or
* not.
* @param role The role to check for.
* @return A boolean indicating if the specified role is paused or not.
*/
function _isPaused(Role role) internal view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
/**
* @notice Internal view function to enforce that the given initial user
* signing key resolves to the given smart wallet when deployed through the
* Dharma Smart Wallet Factory V1. (staging version)
* @param smartWallet address The smart wallet.
* @param initialUserSigningKey address The initial user signing key.
*/
function _isSmartWallet(
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_WALLET_CREATION_CODE_HEADER,
initialUserSigningKey,
_WALLET_CREATION_CODE_FOOTER
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_CREATE2_HEADER, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
function _redeemDDaiIfNecessary(uint256 daiAmountFromReserves) internal {
uint256 daiBalance = _DAI.balanceOf(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_DDAI_EXCHANGER.redeemUnderlyingTo(address(this), additionalDaiRequired);
}
}
function _transferToken(
ERC20Interface token, address to, uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.transfer.selector, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer out failed.'
);
}
function _transferEther(address recipient, uint256 etherAmount) internal {
// Send quoted Ether amount to recipient and revert with reason on failure.
(bool ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _transferInToken(
ERC20Interface token, address from, uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.transferFrom.selector, from, address(this), amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer in failed.'
);
}
function _mintDDai(
uint256 dai, bool sendToCaller
) internal returns (uint256 dDai) {
dDai = _DDAI_EXCHANGER.mintTo(
sendToCaller ? msg.sender : address(this), dai
);
}
function _transferAndRedeemDDai(
uint256 daiEquivalentAmount
) internal returns (uint256 totalDDaiRedeemed) {
// Determine dDai to redeem using exchange rate and daiEquivalentAmount.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
totalDDaiRedeemed = (
(daiEquivalentAmount.mul(1e18)).add(exchangeRate.sub(1)) // NOTE: round up
).div(exchangeRate);
// Transfer the dDai from the caller and revert on failure.
_transferInToken(
ERC20Interface(address(_DDAI)), msg.sender, totalDDaiRedeemed
);
// Redeem the dDai for Dai.
_DDAI_EXCHANGER.redeemUnderlyingTo(address(this), daiEquivalentAmount);
}
function _ensureSmartWallet(
address smartWallet, address initialUserSigningKey
) internal pure {
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Cannot resolve smart wallet using provided signing key."
);
}
function _createPathAndAmounts(
address start, address end, bool routeThroughEther
) internal pure returns (address[] memory, uint256[] memory) {
uint256 pathLength = routeThroughEther ? 3 : 2;
address[] memory path = new address[](pathLength);
path[0] = start;
if (routeThroughEther) {
path[1] = _WETH;
}
path[pathLength - 1] = end;
return (path, new uint256[](pathLength));
}
function _ensurePrimaryRecipientIsSetAndEmitEvent(
address primaryRecipient, string memory asset, uint256 amount
) internal {
if (primaryRecipient == address(0)) {
revert(string(abi.encodePacked(
asset, " does not have a primary recipient assigned."
)));
}
emit Withdrawal(asset, primaryRecipient, amount);
}
/**
* @notice Modifier that throws if called by any account other than the owner
* or the supplied role, or if the caller is not the owner and the role in
* question is paused.
* @param role The role to require unless the caller is the owner.
*/
modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
} | External pure function to get the address of the actual contract instance (i.e. the "storage" foor this contract). return The address of this contract instance./ | function getInstance() external pure returns (address instance) {
instance = address(0x2040F2f2bB228927235Dc24C33e99E3A0a7922c1);
}
| 6,603,034 |
./partial_match/4/0x1799D9F854e4b6BF9C65C8D05cc239d7097b0461/sources/LendingPool.sol | / Prevent resetting the logic name for standalone test deployments. TODO Removed for now, implement after new test suite require( _getSettings().versionsRegistry().hasLogicVersion(aLogicName), "LOGIC_NAME_NOT_EXIST" ); | function _setLogicName(bytes32 aLogicName) internal {
require(logicName() == "", "LOGIC_NAME_ALREADY_SET");
bytes32 slot = LOGIC_NAME_SLOT;
assembly {
sstore(slot, aLogicName)
}
}
| 8,542,592 |
/***
* https://rugby.show
* MIT License
* ===========
*
* Copyright (c) 2020 rugby
*
* 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
*/
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/drafts/Counters.sol
pragma solidity ^0.5.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: contracts/interface/IERC908Usership.sol
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
contract IERC908Usership is IERC165 {
struct UsershipInfo
{
address user;
uint256 start;
uint256 period;
}
event UsershipIssue(uint256 indexed tokenId,address indexed from,uint256 start, uint256 period);
event UsershipReturn(uint256 indexed tokenId,address indexed from,uint256 start, uint256 period);
event UsershipReclaim(uint256 indexed tokenId,address indexed from,uint256 start, uint256 period);
event UsershipTransfer(address indexed from, address indexed to, uint256 indexed tokenId);
event UsershipApproval(address indexed from, address indexed approved, uint256 indexed tokenId);
event UsershipApprovalForAll(address indexed from, address indexed operator, bool approved);
//
function balanceOfUsership(address user) public view returns (uint256 balance);
function getUsershipInfo(uint256 tokenId) public view returns (UsershipInfo memory) ;
function usershipOf(uint256 tokenId) public view returns (address) ;
// function usershipIssue(uint256 tokenId, address to, uint256 period) public ;
// function usershipReturn(uint256 tokenId) public;
// function usershipReclaim(uint256 tokenId,bytes memory data) public;
//
function usershipApprove(address to, uint256 tokenId) public ;
function getUsershipApproved(uint256 tokenId) public view returns (address) ;
function setUsershipApprovalForAll(address to, bool approved) public ;
function isUsershipApprovedForAll(address user, address operator) public view returns (bool) ;
//
function usershipTransfer(address from, address to, uint256 tokenId) public ;
function usershipSafeTransfer(address from, address to, uint256 tokenId) public ;
function usershipSafeTransfer(address from, address to, uint256 tokenId, bytes memory data) public ;
}
// contract Selector {
// function calculateSelector() public pure returns (bytes4,bytes4,bytes4,bytes4,bytes4,bytes4,bytes4,bytes4,bytes4,bytes4) {
// IERC908Usership i;
// return
// (
// i.balanceOfUsership.selector ,
// i.getUsershipInfo.selector ,
// i.usershipOf.selector ,
// i.usershipApprove.selector,
// i.getUsershipApproved.selector ,
// i.setUsershipApprovalForAll.selector ,
// i.isUsershipApprovedForAll.selector ,
// i.usershipTransfer.selector,
// bytes4(keccak256('usershipSafeTransfer(address,addres,uint256)')),
// bytes4(keccak256('usershipSafeTransfer(address,addres,uint256,bytes)'))
// );
// }
// function calculateAllSelector() public pure returns (bytes4) {
// IERC908Usership i;
// return
// (
// i.balanceOfUsership.selector^
// i.getUsershipInfo.selector^
// i.usershipOf.selector^
// i.usershipApprove.selector^
// i.getUsershipApproved.selector^
// i.setUsershipApprovalForAll.selector^
// i.isUsershipApprovedForAll.selector^
// i.usershipTransfer.selector^
// bytes4(keccak256('usershipSafeTransfer(address,addres,uint256)'))^
// bytes4(keccak256('usershipSafeTransfer(address,addres,uint256,bytes)'))
// );
// }
// }
// File: contracts/interface/IERC908Receiver.sol
pragma solidity ^0.5.0;
/**
* @title ERC908 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC908 asset contracts.
*/
contract IERC908Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC908 smart contract calls this function on the recipient
* after a {IERC908-safeLeaseTransfer or safeTransferFrom }. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC908Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC908 contract address is always the message sender.
* @param operator The address which called `safeLeaseTransfer or safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC908Received(address,address,uint256,bytes)"))`
*/
function onERC908Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
/**
* @notice Handle the receipt of an NFT
* @dev The ERC908 smart contract calls this function on the recipient
* after a {IERC908-usershipReclaim}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC908LeaseEnd.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC908 contract address is always the message sender.
* @param operator The address which called `usershipReclaim` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC908LeaseEnd(address,address,uint256,bytes)"))`
*/
function onERC908UsershipReclaim(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// contract Selector {
// function calculateSelector() public pure returns (bytes4,bytes4,bytes4) {
// IERC908Receiver i;
// return
// (
// i.onERC908Received.selector ,
// i.onERC908UsershipReclaim.selector ,
// i.onERC908Received.selector^
// i.onERC908UsershipReclaim.selector
// );
// }
// }
// //0x4e8dce34^0x200c873e==0x6e81490a
// File: contracts/ERC908Usership.sol
pragma solidity ^0.5.5;
//import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract ERC908Usership is Context, ERC165, IERC908Usership {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC908Received(address,address,uint256,bytes)"))`
bytes4 private constant _ERC908_RECEIVED = 0x4e8dce34;
// Equals to `bytes4(keccak256("onERC908UsershipReclaim(address,address,uint256,bytes)"))`
bytes4 private constant _ERC908_RECLAIMED = 0x200c873e;
//for usership
mapping(uint256 => UsershipInfo ) internal _usershipInfo;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _usershipTokensCount;
// Mapping from token ID to usership approved address
mapping (uint256 => address) private _usershipTokenApprovals;
// Mapping from usership to operator approvals
mapping (address => mapping (address => bool)) private _usershipOperatorApprovals;
/*
* => 0xde01ba66^0x8e006e05^0x3e5aedb2^0xb2c818d0^0xa3dc3cd9^0xf6fc46c2^0x70f7988a^0xcc6be08d^0x3c060c58^0xefe2fda4
== 0xe6cbd2e1
*/
bytes4 private constant _INTERFACE_ID_ERC908 = 0xe6cbd2e1;
constructor () public {
// register the supported interfaces to conform to ERC908 via ERC165
_registerInterface(_INTERFACE_ID_ERC908);
}
/**
* @dev Gets the balance of the specified address.
* @param user address to query the balance of
* @return uint256 representing the amount usership by the passed address
*/
function balanceOfUsership(address user) public view returns (uint256) {
require(user != address(0), "ERC908: balance query for the zero address");
return _usershipTokensCount[user].current();
}
/**
* @dev Gets the usership of the specified token ID.
* @param tokenId uint256 ID of the token to query the usership of
* @return address currently marked as the usership of the given token ID
*/
function usershipOf(uint256 tokenId) public view returns (address) {
return _usershipInfo[tokenId].user;
}
/**
* @dev Gets the usership info of the specified token ID.
* @param tokenId uint256 ID of the token to query the usership of
* @return address currently marked as the usership of the given token ID
*/
function getUsershipInfo(uint256 tokenId) public view returns (UsershipInfo memory) {
return _usershipInfo[tokenId];
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token usership or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function usershipApprove(address to, uint256 tokenId) public {
address user = usershipOf(tokenId);
require(to != user, "ERC908: usershipApprove to current user");
require(msg.sender == user || isUsershipApprovedForAll(user, msg.sender),
"ERC908: usershipApprove caller is not usership nor approved for all"
);
_usershipTokenApprovals[tokenId] = to;
emit UsershipApproval(user, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getUsershipApproved(uint256 tokenId) public view returns (address) {
require(_isHasUsership(tokenId), "ERC908: approved query for nonexistent token");
return _usershipTokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to usershiptransfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setUsershipApprovalForAll(address to, bool approved) public {
require(to != msg.sender, "ERC908: approve to caller");
_usershipOperatorApprovals[msg.sender][to] = approved;
emit UsershipApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given usership.
* @param user usership address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given usership
*/
function isUsershipApprovedForAll(address user, address operator) public view returns (bool) {
return _usershipOperatorApprovals[user][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {usershipTransfer} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner or usership of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred by owner or usership
*/
function usershipTransfer(address from, address to, uint256 tokenId) public {
require(_isApprovedOrUsership(msg.sender, tokenId),"ERC908: transfer caller is not owner nor approved");
_usershipTransfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC908Receiver-onERC908Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC908Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, usership, approved, or operator
* @param from current owner or usership of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function usershipSafeTransfer(address from, address to, uint256 tokenId) public {
usershipSafeTransfer(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC908Receiver-onERC908Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC908Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, usership, approved, or operator
* @param from current owner or usership of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function usershipSafeTransfer(address from, address to, uint256 tokenId, bytes memory data) public {
usershipTransfer(from,to,tokenId);
require(_checkOnERC908Received(from, to, tokenId, data), "ERC908: transfer to non ERC908Receiver implementer");
}
/**
* @dev Returns whether the specified token has usership
* @param tokenId uint256 ID of the token to query the usership of
* @return bool whether the token has usership
*/
function _isHasUsership(uint256 tokenId) internal view returns (bool) {
address user = _usershipInfo[tokenId].user;
return user != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the usership, or is the usership of the token
*/
function _isApprovedOrUsership(address spender, uint256 tokenId) internal view returns (bool) {
//require(_isHasUsership(tokenId), "ERC908: operator query for nonexistent token");
if(_isHasUsership(tokenId)==false){
return false;
}
address user = usershipOf(tokenId);
return (spender == user || getUsershipApproved(tokenId) == spender || isUsershipApprovedForAll(user, spender));
}
/**
* @dev public function to issue usership to a new token.
* Reverts if the given token ID already exists.
* @param to The address that will recevie the usership
* @param tokenId uint256 ID of the token to issue usership
*/
function _usershipIssue(uint256 tokenId, address to, uint256 period) internal {
require(to != address(0), "ERC908: mint to the zero address");
require(!_isHasUsership(tokenId), "ERC908: token has usership");
_usershipInfo[tokenId].user = to;
_usershipInfo[tokenId].period = period;
_usershipInfo[tokenId].start = now;
_usershipTokensCount[to].increment();
emit UsershipIssue(tokenId, to, _usershipInfo[tokenId].start,_usershipInfo[tokenId].period );
}
/**
* @dev public function to _terminate a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_terminate} instead.
* @param user user of the token to return
* @param tokenId uint256 ID of the token being return
*/
function _usershipReturn(address user, uint256 tokenId) internal {
require(usershipOf(tokenId) == user, "ERC908: token has not usership");
//uint256 left = now.sub(_usershipInfo[tokenId].start);
//require(left>_usershipInfo[tokenId].period , "ERC908: The usership period has not yet arrived ");
_clearUsershipApproval(tokenId);
emit UsershipReturn(tokenId, user, _usershipInfo[tokenId].start, _usershipInfo[tokenId].period );
_usershipTokensCount[user].decrement();
_usershipInfo[tokenId].user = address(0);
_usershipInfo[tokenId].start = 0;
_usershipInfo[tokenId].period = 0;
}
function _usershipReclaim(uint256 tokenId,bytes memory data) internal
{
if(data.length !=0 ){
require(_checkOnERC908UsershipReclaim(tokenId, data), "ERC908: usership end to non ERC908Receiver implementer");
}
_clearUsershipApproval(tokenId);
address user = _usershipInfo[tokenId].user;
emit UsershipReclaim(tokenId, user, _usershipInfo[tokenId].start, _usershipInfo[tokenId].period );
_usershipTokensCount[user].decrement();
_usershipInfo[tokenId].user = address(0);
_usershipInfo[tokenId].start = 0;
_usershipInfo[tokenId].period = 0;
}
/**
* @dev internal function to initialize usership info of a given token ID.
* @param tokenId uint256 ID of the token to be initialize
*/
function _usershipInitialize(uint256 tokenId) internal {
_usershipInfo[tokenId].user =address(0);
_usershipInfo[tokenId].start =0;
_usershipInfo[tokenId].period =0;
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred by usership
*/
function _usershipTransfer(address from, address to, uint256 tokenId) internal {
require(usershipOf(tokenId) == from, "ERC908: transfer of token that is not own");
require(to != address(0), "ERC908: transfer to the zero address");
_clearUsershipApproval(tokenId);
_usershipTokensCount[from].decrement();
_usershipTokensCount[to].increment();
_usershipInfo[tokenId].user = to;
emit UsershipTransfer(from, to, tokenId);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred by usership
*/
function _clearUsershipApproval(uint256 tokenId) private {
if (_usershipTokenApprovals[tokenId] != address(0)) {
_usershipTokenApprovals[tokenId] = address(0);
}
}
/**
* @dev Internal function to invoke {IERC908Receiver-onERC908Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERC908` contract and its use is deprecated.
* @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 _checkOnERC908Received(address from, address to, uint256 tokenId, bytes memory data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC908Receiver(to).onERC908Received.selector,
_msgSender(),
from,
tokenId,
data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC908: transfer to non ERC908Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC908_RECEIVED);
}
}
/**
* @dev Internal function to invoke {IERC908Receiver-onERC908Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERC908` contract and its use is deprecated.
* @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 _checkOnERC908UsershipReclaim(uint256 tokenId, bytes memory data)
internal returns (bool)
{
address user = _usershipInfo[tokenId].user;
if (!user.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = user.call(abi.encodeWithSelector(
IERC908Receiver(user).onERC908UsershipReclaim.selector,
_msgSender(),
user,
tokenId,
data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC908: lease end to non ERC908Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC908_RECLAIMED);
}
}
}
// File: contracts/interface/IERC908Enumerable.sol
pragma solidity ^0.5.0;
contract IERC908Enumerable is IERC908Usership {
function tokenOfUsershipByIndex(address user, uint256 index) public view returns (uint256 tokenId);
function tokenOfUsership(address user) public view returns (uint256[] memory);
}
// contract Selector {
// function calculateSelector() public pure returns (bytes4,bytes4,bytes4) {
// IERC908Enumerable i;
// return
// (i.tokenOfUsershipByIndex.selector , i.tokenOfUsership.selector ,
// i.tokenOfUsershipByIndex.selector ^ i.tokenOfUsership.selector );
// }
// }
// File: contracts/ERC908Enumerable.sol
pragma solidity ^0.5.0;
contract ERC908Enumerable is Context, ERC165, ERC908Usership, IERC908Enumerable{
// Mapping from usership to list of owned token IDs
mapping(address => uint256[] ) public _usershipTokens;
// Mapping from token ID to index of the usership tokens list
mapping(uint256 => uint256) public _usershipTokensIndex;
/*
* => 0xb060f823 ^ 0x518d1c3b == 0xe1ede418
*/
bytes4 private constant _INTERFACE_ID_ERC908_ENUMERABLE = 0xe1ede418;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC908Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC908_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param user address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfUsershipByIndex(address user, uint256 index) public view returns (uint256) {
require(index < balanceOfUsership(user), "ERC908Enumerable: owner index out of bounds");
return _usershipTokens[user][index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _usershipTransfer(address from, address to, uint256 tokenId) internal {
super._usershipTransfer(from, to, tokenId);
}
/**
* @dev Gets the list of token IDs of the requested user.
* @param user address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function tokenOfUsership(address user) public view returns (uint256[] memory) {
return _usershipTokens[user];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new user of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToUsershipEnumeration(address to, uint256 tokenId) internal {
_usershipTokensIndex[tokenId] = _usershipTokens[to].length;
_usershipTokens[to].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 usership, 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 usership of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromUsershipEnumeration(address from, uint256 tokenId) internal {
// 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 = _usershipTokens[from].length.sub(1);
uint256 tokenIndex = _usershipTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _usershipTokens[from][lastTokenIndex];
_usershipTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_usershipTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_usershipTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
}
| Returns whether the given spender can transfer a given token ID. spender address of the spender to query tokenId uint256 ID of the token to be transferred return bool whether the msg.sender is approved for the given token ID, is an operator of the usership, or is the usership of the token/require(_isHasUsership(tokenId), "ERC908: operator query for nonexistent token"); | function _isApprovedOrUsership(address spender, uint256 tokenId) internal view returns (bool) {
if(_isHasUsership(tokenId)==false){
return false;
}
address user = usershipOf(tokenId);
return (spender == user || getUsershipApproved(tokenId) == spender || isUsershipApprovedForAll(user, spender));
}
| 7,242,505 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
import {ILensHub} from '../interfaces/ILensHub.sol';
import {Events} from '../libraries/Events.sol';
import {Helpers} from '../libraries/Helpers.sol';
import {Constants} from '../libraries/Constants.sol';
import {DataTypes} from '../libraries/DataTypes.sol';
import {Errors} from '../libraries/Errors.sol';
import {PublishingLogic} from '../libraries/PublishingLogic.sol';
import {ProfileTokenURILogic} from '../libraries/ProfileTokenURILogic.sol';
import {InteractionLogic} from '../libraries/InteractionLogic.sol';
import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import {LensNFTBase} from './base/LensNFTBase.sol';
import {LensMultiState} from './base/LensMultiState.sol';
import {LensHubStorage} from './storage/LensHubStorage.sol';
import {VersionedInitializable} from '../upgradeability/VersionedInitializable.sol';
/**
* @title LensHub
* @author Lens Protocol
*
* @notice This is the main entrypoint of the Lens Protocol. It contains governance functionality as well as
* publishing and profile interaction functionality.
*
* NOTE: The Lens Protocol is unique in that frontend operators need to track a potentially overwhelming
* number of NFT contracts and interactions at once. For that reason, we've made two quirky design decisions:
* 1. Both Follow & Collect NFTs invoke an LensHub callback on transfer with the sole purpose of emitting an event.
* 2. Almost every event in the protocol emits the current block timestamp, reducing the need to fetch it manually.
*/
contract LensHub is ILensHub, LensNFTBase, VersionedInitializable, LensMultiState, LensHubStorage {
uint256 internal constant REVISION = 1;
address internal immutable FOLLOW_NFT_IMPL;
address internal immutable COLLECT_NFT_IMPL;
/**
* @dev This modifier reverts if the caller is not the configured governance address.
*/
modifier onlyGov() {
_validateCallerIsGovernance();
_;
}
/**
* @dev This modifier reverts if the caller is not a whitelisted profile creator address.
*/
modifier onlyWhitelistedProfileCreator() {
_validateCallerIsWhitelistedProfileCreator();
_;
}
/**
* @dev The constructor sets the immutable follow & collect NFT implementations.
*
* @param followNFTImpl The follow NFT implementation address.
* @param collectNFTImpl The collect NFT implementation address.
*/
constructor(address followNFTImpl, address collectNFTImpl) {
FOLLOW_NFT_IMPL = followNFTImpl;
COLLECT_NFT_IMPL = collectNFTImpl;
}
/// @inheritdoc ILensHub
function initialize(
string calldata name,
string calldata symbol,
address newGovernance
) external override initializer {
super._initialize(name, symbol);
_setState(DataTypes.ProtocolState.Paused);
_setGovernance(newGovernance);
}
/// ***********************
/// *****GOV FUNCTIONS*****
/// ***********************
/// @inheritdoc ILensHub
function setGovernance(address newGovernance) external override onlyGov {
_setGovernance(newGovernance);
}
/// @inheritdoc ILensHub
function setEmergencyAdmin(address newEmergencyAdmin) external override onlyGov {
address prevEmergencyAdmin = _emergencyAdmin;
_emergencyAdmin = newEmergencyAdmin;
emit Events.EmergencyAdminSet(
msg.sender,
prevEmergencyAdmin,
newEmergencyAdmin,
block.timestamp
);
}
/// @inheritdoc ILensHub
function setState(DataTypes.ProtocolState newState) external override {
if (msg.sender != _governance && msg.sender != _emergencyAdmin)
revert Errors.NotGovernanceOrEmergencyAdmin();
_setState(newState);
}
///@inheritdoc ILensHub
function whitelistProfileCreator(address profileCreator, bool whitelist)
external
override
onlyGov
{
_profileCreatorWhitelisted[profileCreator] = whitelist;
emit Events.ProfileCreatorWhitelisted(profileCreator, whitelist, block.timestamp);
}
/// @inheritdoc ILensHub
function whitelistFollowModule(address followModule, bool whitelist) external override onlyGov {
_followModuleWhitelisted[followModule] = whitelist;
emit Events.FollowModuleWhitelisted(followModule, whitelist, block.timestamp);
}
/// @inheritdoc ILensHub
function whitelistReferenceModule(address referenceModule, bool whitelist)
external
override
onlyGov
{
_referenceModuleWhitelisted[referenceModule] = whitelist;
emit Events.ReferenceModuleWhitelisted(referenceModule, whitelist, block.timestamp);
}
/// @inheritdoc ILensHub
function whitelistCollectModule(address collectModule, bool whitelist)
external
override
onlyGov
{
_collectModuleWhitelisted[collectModule] = whitelist;
emit Events.CollectModuleWhitelisted(collectModule, whitelist, block.timestamp);
}
/// *********************************
/// *****PROFILE OWNER FUNCTIONS*****
/// *********************************
/// @inheritdoc ILensHub
function createProfile(DataTypes.CreateProfileData calldata vars)
external
override
whenNotPaused
onlyWhitelistedProfileCreator
{
uint256 profileId = ++_profileCounter;
_mint(vars.to, profileId);
PublishingLogic.createProfile(
vars,
profileId,
_profileIdByHandleHash,
_profileById,
_followModuleWhitelisted
);
}
/// @inheritdoc ILensHub
function setDefaultProfile(uint256 profileId) external override whenNotPaused {
_setDefaultProfile(msg.sender, profileId);
}
/// @inheritdoc ILensHub
function setDefaultProfileWithSig(DataTypes.SetDefaultProfileWithSigData calldata vars)
external
override
whenNotPaused
{
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
SET_DEFAULT_PROFILE_WITH_SIG_TYPEHASH,
vars.wallet,
vars.profileId,
sigNonces[vars.wallet]++,
vars.sig.deadline
)
)
),
vars.wallet,
vars.sig
);
_setDefaultProfile(vars.wallet, vars.profileId);
}
/// @inheritdoc ILensHub
function setFollowModule(
uint256 profileId,
address followModule,
bytes calldata followModuleData
) external override whenNotPaused {
_validateCallerIsProfileOwner(profileId);
PublishingLogic.setFollowModule(
profileId,
followModule,
followModuleData,
_profileById[profileId],
_followModuleWhitelisted
);
}
/// @inheritdoc ILensHub
function setFollowModuleWithSig(DataTypes.SetFollowModuleWithSigData calldata vars)
external
override
whenNotPaused
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
SET_FOLLOW_MODULE_WITH_SIG_TYPEHASH,
vars.profileId,
vars.followModule,
keccak256(vars.followModuleData),
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
PublishingLogic.setFollowModule(
vars.profileId,
vars.followModule,
vars.followModuleData,
_profileById[vars.profileId],
_followModuleWhitelisted
);
}
/// @inheritdoc ILensHub
function setDispatcher(uint256 profileId, address dispatcher) external override whenNotPaused {
_validateCallerIsProfileOwner(profileId);
_setDispatcher(profileId, dispatcher);
}
/// @inheritdoc ILensHub
function setDispatcherWithSig(DataTypes.SetDispatcherWithSigData calldata vars)
external
override
whenNotPaused
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
SET_DISPATCHER_WITH_SIG_TYPEHASH,
vars.profileId,
vars.dispatcher,
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
_setDispatcher(vars.profileId, vars.dispatcher);
}
/// @inheritdoc ILensHub
function setProfileImageURI(uint256 profileId, string calldata imageURI)
external
override
whenNotPaused
{
_validateCallerIsProfileOwnerOrDispatcher(profileId);
_setProfileImageURI(profileId, imageURI);
}
/// @inheritdoc ILensHub
function setProfileImageURIWithSig(DataTypes.SetProfileImageURIWithSigData calldata vars)
external
override
whenNotPaused
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
SET_PROFILE_IMAGE_URI_WITH_SIG_TYPEHASH,
vars.profileId,
keccak256(bytes(vars.imageURI)),
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
_setProfileImageURI(vars.profileId, vars.imageURI);
}
/// @inheritdoc ILensHub
function setFollowNFTURI(uint256 profileId, string calldata followNFTURI)
external
override
whenNotPaused
{
_validateCallerIsProfileOwnerOrDispatcher(profileId);
_setFollowNFTURI(profileId, followNFTURI);
}
/// @inheritdoc ILensHub
function setFollowNFTURIWithSig(DataTypes.SetFollowNFTURIWithSigData calldata vars)
external
override
whenNotPaused
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
SET_FOLLOW_NFT_URI_WITH_SIG_TYPEHASH,
vars.profileId,
keccak256(bytes(vars.followNFTURI)),
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
_setFollowNFTURI(vars.profileId, vars.followNFTURI);
}
/// @inheritdoc ILensHub
function post(DataTypes.PostData calldata vars) external override whenPublishingEnabled {
_validateCallerIsProfileOwnerOrDispatcher(vars.profileId);
_createPost(
vars.profileId,
vars.contentURI,
vars.collectModule,
vars.collectModuleData,
vars.referenceModule,
vars.referenceModuleData
);
}
/// @inheritdoc ILensHub
function postWithSig(DataTypes.PostWithSigData calldata vars)
external
override
whenPublishingEnabled
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
POST_WITH_SIG_TYPEHASH,
vars.profileId,
keccak256(bytes(vars.contentURI)),
vars.collectModule,
keccak256(vars.collectModuleData),
vars.referenceModule,
keccak256(vars.referenceModuleData),
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
_createPost(
vars.profileId,
vars.contentURI,
vars.collectModule,
vars.collectModuleData,
vars.referenceModule,
vars.referenceModuleData
);
}
/// @inheritdoc ILensHub
function comment(DataTypes.CommentData calldata vars) external override whenPublishingEnabled {
_validateCallerIsProfileOwnerOrDispatcher(vars.profileId);
_createComment(vars);
}
/// @inheritdoc ILensHub
function commentWithSig(DataTypes.CommentWithSigData calldata vars)
external
override
whenPublishingEnabled
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
COMMENT_WITH_SIG_TYPEHASH,
vars.profileId,
keccak256(bytes(vars.contentURI)),
vars.profileIdPointed,
vars.pubIdPointed,
vars.collectModule,
keccak256(vars.collectModuleData),
vars.referenceModule,
keccak256(vars.referenceModuleData),
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
_createComment(
DataTypes.CommentData(
vars.profileId,
vars.contentURI,
vars.profileIdPointed,
vars.pubIdPointed,
vars.collectModule,
vars.collectModuleData,
vars.referenceModule,
vars.referenceModuleData
)
);
}
/// @inheritdoc ILensHub
function mirror(DataTypes.MirrorData calldata vars) external override whenPublishingEnabled {
_validateCallerIsProfileOwnerOrDispatcher(vars.profileId);
_createMirror(
vars.profileId,
vars.profileIdPointed,
vars.pubIdPointed,
vars.referenceModule,
vars.referenceModuleData
);
}
/// @inheritdoc ILensHub
function mirrorWithSig(DataTypes.MirrorWithSigData calldata vars)
external
override
whenPublishingEnabled
{
address owner = ownerOf(vars.profileId);
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
MIRROR_WITH_SIG_TYPEHASH,
vars.profileId,
vars.profileIdPointed,
vars.pubIdPointed,
vars.referenceModule,
keccak256(vars.referenceModuleData),
sigNonces[owner]++,
vars.sig.deadline
)
)
),
owner,
vars.sig
);
_createMirror(
vars.profileId,
vars.profileIdPointed,
vars.pubIdPointed,
vars.referenceModule,
vars.referenceModuleData
);
}
/**
* @notice Burns a profile, this maintains the profile data struct, but deletes the
* handle hash to profile ID mapping value.
*
* NOTE: This overrides the LensNFTBase contract's `burn()` function and calls it to fully burn
* the NFT.
*/
function burn(uint256 tokenId) public override whenNotPaused {
super.burn(tokenId);
_clearHandleHash(tokenId);
}
/**
* @notice Burns a profile with a signature, this maintains the profile data struct, but deletes the
* handle hash to profile ID mapping value.
*
* NOTE: This overrides the LensNFTBase contract's `burnWithSig()` function and calls it to fully burn
* the NFT.
*/
function burnWithSig(uint256 tokenId, DataTypes.EIP712Signature calldata sig)
public
override
whenNotPaused
{
super.burnWithSig(tokenId, sig);
_clearHandleHash(tokenId);
}
/// ***************************************
/// *****PROFILE INTERACTION FUNCTIONS*****
/// ***************************************
/// @inheritdoc ILensHub
function follow(uint256[] calldata profileIds, bytes[] calldata datas)
external
override
whenNotPaused
{
InteractionLogic.follow(
msg.sender,
profileIds,
datas,
FOLLOW_NFT_IMPL,
_profileById,
_profileIdByHandleHash
);
}
/// @inheritdoc ILensHub
function followWithSig(DataTypes.FollowWithSigData calldata vars)
external
override
whenNotPaused
{
bytes32[] memory dataHashes = new bytes32[](vars.datas.length);
for (uint256 i = 0; i < vars.datas.length; ++i) {
dataHashes[i] = keccak256(vars.datas[i]);
}
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
FOLLOW_WITH_SIG_TYPEHASH,
keccak256(abi.encodePacked(vars.profileIds)),
keccak256(abi.encodePacked(dataHashes)),
sigNonces[vars.follower]++,
vars.sig.deadline
)
)
),
vars.follower,
vars.sig
);
InteractionLogic.follow(
vars.follower,
vars.profileIds,
vars.datas,
FOLLOW_NFT_IMPL,
_profileById,
_profileIdByHandleHash
);
}
/// @inheritdoc ILensHub
function collect(
uint256 profileId,
uint256 pubId,
bytes calldata data
) external override whenNotPaused {
InteractionLogic.collect(
msg.sender,
profileId,
pubId,
data,
COLLECT_NFT_IMPL,
_pubByIdByProfile,
_profileById
);
}
/// @inheritdoc ILensHub
function collectWithSig(DataTypes.CollectWithSigData calldata vars)
external
override
whenNotPaused
{
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
COLLECT_WITH_SIG_TYPEHASH,
vars.profileId,
vars.pubId,
keccak256(vars.data),
sigNonces[vars.collector]++,
vars.sig.deadline
)
)
),
vars.collector,
vars.sig
);
InteractionLogic.collect(
vars.collector,
vars.profileId,
vars.pubId,
vars.data,
COLLECT_NFT_IMPL,
_pubByIdByProfile,
_profileById
);
}
/// @inheritdoc ILensHub
function emitFollowNFTTransferEvent(
uint256 profileId,
uint256 followNFTId,
address from,
address to
) external override {
address expectedFollowNFT = _profileById[profileId].followNFT;
if (msg.sender != expectedFollowNFT) revert Errors.CallerNotFollowNFT();
emit Events.FollowNFTTransferred(profileId, followNFTId, from, to, block.timestamp);
}
/// @inheritdoc ILensHub
function emitCollectNFTTransferEvent(
uint256 profileId,
uint256 pubId,
uint256 collectNFTId,
address from,
address to
) external override {
address expectedCollectNFT = _pubByIdByProfile[profileId][pubId].collectNFT;
if (msg.sender != expectedCollectNFT) revert Errors.CallerNotCollectNFT();
emit Events.CollectNFTTransferred(
profileId,
pubId,
collectNFTId,
from,
to,
block.timestamp
);
}
/// *********************************
/// *****EXTERNAL VIEW FUNCTIONS*****
/// *********************************
/// @inheritdoc ILensHub
function isProfileCreatorWhitelisted(address profileCreator)
external
view
override
returns (bool)
{
return _profileCreatorWhitelisted[profileCreator];
}
/// @inheritdoc ILensHub
function defaultProfile(address wallet) external view override returns (uint256) {
return _defaultProfileByAddress[wallet];
}
/// @inheritdoc ILensHub
function isFollowModuleWhitelisted(address followModule) external view override returns (bool) {
return _followModuleWhitelisted[followModule];
}
/// @inheritdoc ILensHub
function isReferenceModuleWhitelisted(address referenceModule)
external
view
override
returns (bool)
{
return _referenceModuleWhitelisted[referenceModule];
}
/// @inheritdoc ILensHub
function isCollectModuleWhitelisted(address collectModule)
external
view
override
returns (bool)
{
return _collectModuleWhitelisted[collectModule];
}
/// @inheritdoc ILensHub
function getGovernance() external view override returns (address) {
return _governance;
}
/// @inheritdoc ILensHub
function getDispatcher(uint256 profileId) external view override returns (address) {
return _dispatcherByProfile[profileId];
}
/// @inheritdoc ILensHub
function getPubCount(uint256 profileId) external view override returns (uint256) {
return _profileById[profileId].pubCount;
}
/// @inheritdoc ILensHub
function getFollowNFT(uint256 profileId) external view override returns (address) {
return _profileById[profileId].followNFT;
}
/// @inheritdoc ILensHub
function getFollowNFTURI(uint256 profileId) external view override returns (string memory) {
return _profileById[profileId].followNFTURI;
}
/// @inheritdoc ILensHub
function getCollectNFT(uint256 profileId, uint256 pubId)
external
view
override
returns (address)
{
return _pubByIdByProfile[profileId][pubId].collectNFT;
}
/// @inheritdoc ILensHub
function getFollowModule(uint256 profileId) external view override returns (address) {
return _profileById[profileId].followModule;
}
/// @inheritdoc ILensHub
function getCollectModule(uint256 profileId, uint256 pubId)
external
view
override
returns (address)
{
return _pubByIdByProfile[profileId][pubId].collectModule;
}
/// @inheritdoc ILensHub
function getReferenceModule(uint256 profileId, uint256 pubId)
external
view
override
returns (address)
{
return _pubByIdByProfile[profileId][pubId].referenceModule;
}
/// @inheritdoc ILensHub
function getHandle(uint256 profileId) external view override returns (string memory) {
return _profileById[profileId].handle;
}
/// @inheritdoc ILensHub
function getPubPointer(uint256 profileId, uint256 pubId)
external
view
override
returns (uint256, uint256)
{
uint256 profileIdPointed = _pubByIdByProfile[profileId][pubId].profileIdPointed;
uint256 pubIdPointed = _pubByIdByProfile[profileId][pubId].pubIdPointed;
return (profileIdPointed, pubIdPointed);
}
/// @inheritdoc ILensHub
function getContentURI(uint256 profileId, uint256 pubId)
external
view
override
returns (string memory)
{
(uint256 rootProfileId, uint256 rootPubId, ) = Helpers.getPointedIfMirror(
profileId,
pubId,
_pubByIdByProfile
);
return _pubByIdByProfile[rootProfileId][rootPubId].contentURI;
}
/// @inheritdoc ILensHub
function getProfileIdByHandle(string calldata handle) external view override returns (uint256) {
bytes32 handleHash = keccak256(bytes(handle));
return _profileIdByHandleHash[handleHash];
}
/// @inheritdoc ILensHub
function getProfile(uint256 profileId)
external
view
override
returns (DataTypes.ProfileStruct memory)
{
return _profileById[profileId];
}
/// @inheritdoc ILensHub
function getPub(uint256 profileId, uint256 pubId)
external
view
override
returns (DataTypes.PublicationStruct memory)
{
return _pubByIdByProfile[profileId][pubId];
}
/// @inheritdoc ILensHub
function getPubType(uint256 profileId, uint256 pubId)
external
view
override
returns (DataTypes.PubType)
{
if (pubId == 0 || _profileById[profileId].pubCount < pubId) {
return DataTypes.PubType.Nonexistent;
} else if (_pubByIdByProfile[profileId][pubId].collectModule == address(0)) {
return DataTypes.PubType.Mirror;
} else {
if (_pubByIdByProfile[profileId][pubId].profileIdPointed == 0) {
return DataTypes.PubType.Post;
} else {
return DataTypes.PubType.Comment;
}
}
}
/**
* @dev Overrides the ERC721 tokenURI function to return the associated URI with a given profile.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
address followNFT = _profileById[tokenId].followNFT;
return
ProfileTokenURILogic.getProfileTokenURI(
tokenId,
followNFT == address(0) ? 0 : IERC721Enumerable(followNFT).totalSupply(),
ownerOf(tokenId),
_profileById[tokenId].handle,
_profileById[tokenId].imageURI
);
}
/// ****************************
/// *****INTERNAL FUNCTIONS*****
/// ****************************
function _setGovernance(address newGovernance) internal {
address prevGovernance = _governance;
_governance = newGovernance;
emit Events.GovernanceSet(msg.sender, prevGovernance, newGovernance, block.timestamp);
}
function _createPost(
uint256 profileId,
string memory contentURI,
address collectModule,
bytes memory collectModuleData,
address referenceModule,
bytes memory referenceModuleData
) internal {
PublishingLogic.createPost(
profileId,
contentURI,
collectModule,
collectModuleData,
referenceModule,
referenceModuleData,
++_profileById[profileId].pubCount,
_pubByIdByProfile,
_collectModuleWhitelisted,
_referenceModuleWhitelisted
);
}
function _setDefaultProfile(address wallet, uint256 profileId) internal {
if (profileId > 0) {
if (wallet != ownerOf(profileId)) revert Errors.NotProfileOwner();
}
_defaultProfileByAddress[wallet] = profileId;
emit Events.DefaultProfileSet(wallet, profileId, block.timestamp);
}
function _createComment(DataTypes.CommentData memory vars) internal {
PublishingLogic.createComment(
vars,
_profileById[vars.profileId].pubCount + 1,
_profileById,
_pubByIdByProfile,
_collectModuleWhitelisted,
_referenceModuleWhitelisted
);
_profileById[vars.profileId].pubCount++;
}
function _createMirror(
uint256 profileId,
uint256 profileIdPointed,
uint256 pubIdPointed,
address referenceModule,
bytes calldata referenceModuleData
) internal {
PublishingLogic.createMirror(
profileId,
profileIdPointed,
pubIdPointed,
referenceModule,
referenceModuleData,
++_profileById[profileId].pubCount,
_pubByIdByProfile,
_referenceModuleWhitelisted
);
}
function _setDispatcher(uint256 profileId, address dispatcher) internal {
_dispatcherByProfile[profileId] = dispatcher;
emit Events.DispatcherSet(profileId, dispatcher, block.timestamp);
}
function _setProfileImageURI(uint256 profileId, string memory imageURI) internal {
if (bytes(imageURI).length > Constants.MAX_PROFILE_IMAGE_URI_LENGTH)
revert Errors.ProfileImageURILengthInvalid();
_profileById[profileId].imageURI = imageURI;
emit Events.ProfileImageURISet(profileId, imageURI, block.timestamp);
}
function _setFollowNFTURI(uint256 profileId, string memory followNFTURI) internal {
_profileById[profileId].followNFTURI = followNFTURI;
emit Events.FollowNFTURISet(profileId, followNFTURI, block.timestamp);
}
function _clearHandleHash(uint256 profileId) internal {
bytes32 handleHash = keccak256(bytes(_profileById[profileId].handle));
_profileIdByHandleHash[handleHash] = 0;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override whenNotPaused {
if (_dispatcherByProfile[tokenId] != address(0)) {
_setDispatcher(tokenId, address(0));
}
if (_defaultProfileByAddress[from] == tokenId) {
_defaultProfileByAddress[from] = 0;
}
super._beforeTokenTransfer(from, to, tokenId);
}
function _validateCallerIsProfileOwnerOrDispatcher(uint256 profileId) internal view {
if (msg.sender != ownerOf(profileId) && msg.sender != _dispatcherByProfile[profileId])
revert Errors.NotProfileOwnerOrDispatcher();
}
function _validateCallerIsProfileOwner(uint256 profileId) internal view {
if (msg.sender != ownerOf(profileId)) revert Errors.NotProfileOwner();
}
function _validateCallerIsGovernance() internal view {
if (msg.sender != _governance) revert Errors.NotGovernance();
}
function _validateCallerIsWhitelistedProfileCreator() internal view {
if (!_profileCreatorWhitelisted[msg.sender]) revert Errors.ProfileCreatorNotWhitelisted();
}
function getRevision() internal pure virtual override returns (uint256) {
return REVISION;
}
}
| @inheritdoc ILensHub | function createProfile(DataTypes.CreateProfileData calldata vars)
external
override
whenNotPaused
onlyWhitelistedProfileCreator
{
uint256 profileId = ++_profileCounter;
_mint(vars.to, profileId);
PublishingLogic.createProfile(
vars,
profileId,
_profileIdByHandleHash,
_profileById,
_followModuleWhitelisted
);
}
| 12,861,943 |
// SPDX-License-Identifier: 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";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.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 MemberCard is Context, ERC165, IERC721, IERC721Metadata, Initializable, ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address;
using Strings for uint256;
struct Membership {
uint256 startTime;
uint256 expireTime;
uint256 counter;
}
// 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;
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
mapping(uint256 => string) private _tokenURIs;
uint256 private _buyFees;
address private _owner;
uint256 private _currentBatch;
mapping(address => mapping(uint256 => bool)) private _batchParticipation;
mapping(uint256 => Membership) private _membership;
mapping(uint256 => bool) private _frozen;
mapping(uint256 => bool) private _transferRestriction;
mapping(address => bool) private _vendors;
uint256 private _tokenCounter;
uint256 private _maxTokenCounter;
IERC20 private _paymentToken;
address private treasury;
mapping(address => bool) private _admins;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event SetAdmin(address indexed user, bool indexed allow);
event SetTreasury(address indexed oldTreasury, address indexed newTreasury);
event SetFreezeStatus(uint256 indexed tokenId, bool indexed frozen);
event SetStartTime(uint256 indexed tokenId, uint256 indexed time);
event SetExpireTime(uint256 indexed tokenId, uint256 indexed time);
event SetCounter(uint256 indexed tokenId, uint256 indexed counter);
event SetTransferRestriction(uint256 indexed tokenId, bool indexed allow);
event SetVendor(address indexed vendor, bool indexed allow);
event SetNewBatchTokens(uint256 indexed tokensToAdd);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor() {}
function initialize(address owner_, string memory name_, string memory symbol_) public initializer {
_paymentToken = IERC20(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56);
_setOwner(owner_);
treasury = 0x35b119730F79881DAc623dc51c831C6A04cAB5f3;
_name = name_;
_symbol = symbol_;
_buyFees = 1e20;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
modifier onlyAdmin() {
require((owner() == _msgSender() || _admins[_msgSender()]), "Ownable: caller is not an admin");
_;
}
modifier onlyVendor() {
require(_vendors[_msgSender()], "NFT: caller is not a vendor.");
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
function setAdmin(address user, bool allow) public onlyOwner {
_admins[user] = allow;
emit SetAdmin(user, allow);
}
// custom functions
function setTreasury(address account) public virtual onlyAdmin {
address oldTreasury = treasury;
treasury = account;
emit SetTreasury(oldTreasury, treasury);
}
function setFreezeStatus(uint256 tokenId, bool frozen) public virtual onlyAdmin {
_frozen[tokenId] = frozen;
emit SetFreezeStatus(tokenId, frozen);
}
function setStartTime(uint256 tokenId, uint256 time) public virtual onlyAdmin {
_membership[tokenId].startTime = time;
emit SetStartTime(tokenId, time);
}
function setExpireTime(uint256 tokenId, uint256 time) public virtual onlyAdmin {
_membership[tokenId].expireTime = time;
emit SetExpireTime(tokenId, time);
}
function setCounter(uint256 tokenId, uint256 counter) public virtual onlyAdmin {
_membership[tokenId].counter = counter;
emit SetCounter(tokenId, counter);
}
function setTransferRestriction(uint256 tokenId, bool allow) public virtual onlyAdmin {
_transferRestriction[tokenId] = allow;
emit SetTransferRestriction(tokenId, allow);
}
function setVendor(address vendor, bool allow) public virtual onlyAdmin {
_vendors[vendor] = allow;
emit SetVendor(vendor, allow);
}
function setNewBatchTokens(uint256 tokensToAdd) public virtual onlyAdmin {
_maxTokenCounter = tokensToAdd;
_currentBatch = _currentBatch+1;
emit SetNewBatchTokens(tokensToAdd);
}
// assumes blind Trust on vendor contract as they are part of the ecosystem
function consumeMembership(uint256 tokenId) public virtual onlyVendor {
require(_membership[tokenId].counter >0, "Member Card has been used. Purchase a new one to avail the benefits.");
require(_membership[tokenId].expireTime >block.timestamp, "Member Card has been expired. Purchase a new one to avail the benefits.");
require(!_frozen[tokenId], "Member Card has been frozen.");
_membership[tokenId].counter = _membership[tokenId].counter-1;
}
function mintMemberCard(uint256 startTime, uint256 expireTime, uint256 counter, address user, string memory tokenURI_) public virtual onlyAdmin {
uint256 tokenId = _tokenCounter;
_mint(user, tokenId);
_setTokenURI(tokenId, tokenURI_);
_membership[tokenId] = Membership(startTime, expireTime, counter);
_tokenCounter++;
}
function mintMemberCard(address user, string memory tokenURI_) public virtual onlyAdmin {
uint256 tokenId = _tokenCounter;
_mint(user, tokenId);
_setTokenURI(tokenId, tokenURI_);
_membership[tokenId] = Membership(block.timestamp, block.timestamp + 90 days, 3);
_tokenCounter++;
}
function getMemberCardActive(uint256 tokenId) public view returns(bool) {
bool active = (_membership[tokenId].counter >0 && _membership[tokenId].expireTime >block.timestamp && !_frozen[tokenId]);
return active;
}
function getMemberCardStartTime(uint256 tokenId) public view returns(uint256) {
return _membership[tokenId].startTime;
}
function getMemberCardExpireTime(uint256 tokenId) public view returns(uint256) {
return _membership[tokenId].expireTime;
}
function getMemberCardCounter(uint256 tokenId) public view returns(uint256) {
return _membership[tokenId].counter;
}
function getTokenCounter() public view returns(uint256) {
return _maxTokenCounter;
}
function isMember(address user) public view returns(bool) {
uint256 balance = MemberCard.balanceOf(user);
bool member;
uint256 tid;
for (uint256 i = 0; i < balance; i++){
tid = tokenOfOwnerByIndex(user, i);
bool allow = getMemberCardActive(tid);
if (allow) {
return true;
}
}
return member;
}
function activateMemberCard(uint256 tokenId, uint256 startTime, uint256 expireTime, uint256 counter, string memory tokenURI_) public virtual onlyAdmin {
_setTokenURI(tokenId, tokenURI_);
_membership[tokenId] = Membership(startTime, expireTime, counter);
}
function buy() public virtual nonReentrant {
require(!_batchParticipation[_msgSender()][_currentBatch], "User already own an active Access Key in the current Batch.");
uint256 tokenId = _tokenCounter;
require(tokenId < _maxTokenCounter, "No more NFTs can be bought in the current batch.");
_paymentToken.safeTransferFrom(_msgSender(), treasury, _buyFees);
_mint(_msgSender(), tokenId);
_batchParticipation[_msgSender()][_currentBatch] = true;
_tokenCounter++;
}
function prize(address user) onlyAdmin public virtual {
require(!_batchParticipation[user][_currentBatch], "User already own an active Access Key in the current Batch.");
uint256 tokenId = _tokenCounter;
require(tokenId < _maxTokenCounter, "No more NFTs can be bought in the current batch.");
_mint(user, tokenId);
_batchParticipation[user][_currentBatch] = true;
_tokenCounter++;
}
/**
* @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),
"ERC721: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721URIStorage: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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_ = MemberCard.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_ = MemberCard.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_ = MemberCard.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(MemberCard.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);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(MemberCard.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;
}
}
function tokenOfOwnerByIndex(address owner_, uint256 index)
public
view
virtual
returns (uint256)
{
require(
index < MemberCard.balanceOf(owner_),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner_][index];
}
function totalSupply() public view virtual returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index)
public
view
virtual
returns (uint256)
{
require(
index < MemberCard.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = MemberCard.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
uint256 lastTokenIndex = MemberCard.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @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 {
require((_transferRestriction[tokenId] || from == address(0)), "NFT cannot be transferred, ask admin to grant approval.");
_transferRestriction[tokenId] = false;
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);
}
}
function setBuyFees(uint256 fees) public virtual onlyAdmin {
_buyFees = fees;
}
}
| Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals | function _burn(uint256 tokenId) internal virtual {
address owner_ = MemberCard.ownerOf(tokenId);
_beforeTokenTransfer(owner_, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner_] -= 1;
delete _owners[tokenId];
emit Transfer(owner_, address(0), tokenId);
}
| 2,536,179 |
./full_match/43113/0x4291CeD08B50851cCc23033260076171cF36c9c6/sources/contracts/ERC20_HW2TOKEN.sol | Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `to` cannot be the zero address./ | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
require(_totalSupply == 0, "Tokens can be minted only once.");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
| 7,186,282 |
./partial_match/97/0xdd1E47CD8b9aC215f9c22bCC04552FE70B1F7456/sources/utils/Ownable.sol | 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;
_previousOwner = newOwner;
}
| 11,404,247 |
./full_match/84531/0x575b832b9Be5660A372A56eB3375Ae2E72F9cfb5/sources/contracts/Soulbind.sol | Update token limit for non restricted tokens | function incraseLimit(bytes32 eventId, uint256 limit)
public
validateOwnership(eventId)
{
require(
!createdTokens[eventId].restricted,
"Must not be restricted token"
);
require(createdTokens[eventId].limit < limit, "Increase limit");
require(limit <= _limitMax, "Reduce limit");
createdTokens[eventId].limit = limit;
}
| 14,293,799 |
pragma solidity ^0.5.17;
// 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);
}
}
/*
* 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);
}
/*
* 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);
}
// 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/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);
}
}
// 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;
}
}
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;
}
}
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];
}
}
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 AragonCourt is IArbitrator, Controller {
using Uint256Helpers for uint256;
/**
* @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
Controller(
_termParams,
_governors,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
)
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @notice Create a dispute with `_possibleRulings` possible rulings
* @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(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256) {
IArbitrable subject = IArbitrable(msg.sender);
return _disputeManager().createDispute(subject, _possibleRulings.toUint8(), _metadata);
}
/**
* @notice Submit `_evidence` as evidence from `_submitter` for dispute #`_disputeId`
* @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 {
_submitEvidence(_disputeManager(), _disputeId, _submitter, _evidence);
}
/**
* @notice Submit `_evidence` as evidence from `_submitter` for dispute #`_disputeId`
* @dev This entry point can be used to submit evidences to previous Dispute Manager instances
* @param _disputeManager Dispute manager to be used
* @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 submitEvidenceForModule(IDisputeManager _disputeManager, uint256 _disputeId, address _submitter, bytes calldata _evidence)
external
onlyActiveDisputeManager(_disputeManager)
{
_submitEvidence(_disputeManager, _disputeId, _submitter, _evidence);
}
/**
* @notice Close the evidence period of dispute #`_disputeId`
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external {
_closeEvidencePeriod(_disputeManager(), _disputeId);
}
/**
* @notice Close the evidence period of dispute #`_disputeId`
* @dev This entry point can be used to close evidence periods on previous Dispute Manager instances
* @param _disputeManager Dispute manager to be used
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriodForModule(IDisputeManager _disputeManager, uint256 _disputeId)
external
onlyActiveDisputeManager(_disputeManager)
{
_closeEvidencePeriod(_disputeManager, _disputeId);
}
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Arbitrable instance associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling) {
return _rule(_disputeManager(), _disputeId);
}
/**
* @notice Rule dispute #`_disputeId` if ready
* @dev This entry point can be used to rule disputes on previous Dispute Manager instances
* @param _disputeManager Dispute manager to be used
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Arbitrable instance associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function ruleForModule(IDisputeManager _disputeManager, uint256 _disputeId)
external
onlyActiveDisputeManager(_disputeManager)
returns (address subject, uint256 ruling)
{
return _rule(_disputeManager, _disputeId);
}
/**
* @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) {
IDisputeManager disputeManager = _disputeManager();
recipient = address(disputeManager);
(feeToken, feeAmount) = disputeManager.getDisputeFees();
}
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address) {
return currentModules[MODULE_ID_PAYMENTS_BOOK];
}
/**
* @dev Internal function to submit evidence for a dispute
* @param _disputeManager Dispute manager to be used
* @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(IDisputeManager _disputeManager, uint256 _disputeId, address _submitter, bytes memory _evidence) internal {
IArbitrable subject = IArbitrable(msg.sender);
_disputeManager.submitEvidence(subject, _disputeId, _submitter, _evidence);
}
/**
* @dev Internal function to close the evidence period of a dispute
* @param _disputeManager Dispute manager to be used
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function _closeEvidencePeriod(IDisputeManager _disputeManager, uint256 _disputeId) internal {
IArbitrable subject = IArbitrable(msg.sender);
_disputeManager.closeEvidencePeriod(subject, _disputeId);
}
/**
* @dev Internal function to rule a dispute
* @param _disputeManager Dispute manager to be used
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Arbitrable instance associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function _rule(IDisputeManager _disputeManager, uint256 _disputeId) internal returns (address subject, uint256 ruling) {
(IArbitrable _subject, uint8 _ruling) = _disputeManager.computeRuling(_disputeId);
return (address(_subject), uint256(_ruling));
}
/**
* @dev Internal function to tell the current DisputeManager module
* @return Current DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getModuleAddress(MODULE_ID_DISPUTE_MANAGER));
}
} | Create a dispute with `_possibleRulings` possible rulings _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute _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) {
IArbitrable subject = IArbitrable(msg.sender);
return _disputeManager().createDispute(subject, _possibleRulings.toUint8(), _metadata);
}
| 1,566,091 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract Supa is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public adminAddress; // owner/admin/manager address;
address payable public feesVault; // address where fees will be transferred. This fee is used to pay for devs/marketing etc;
address payable public investmentVault; // address where user funds after fees will go to. ($10 per share, usdc)
address payable public rewardsVault; // address where user rewards will be moved to initially before being claiming.
address public paymentTokenAddress;
uint8 feePercent = 5;
bool isContractLocked = true;
constructor(
address admin,
address feesAddress,
address investmentAddress,
address rewardsAddress,
address tokenAddress
) {
require(
admin != feesAddress &&
feesAddress != investmentAddress &&
investmentAddress != rewardsAddress,
"all addreses must be different"
);
adminAddress = admin;
feesVault = payable(feesAddress);
investmentVault = payable(investmentAddress);
rewardsVault = payable(rewardsAddress);
paymentTokenAddress = tokenAddress;
}
// accounts which are used to create atlas/strongblock nodes.
// We need multiple wallets because there is a hard limit of 100 nodes for strongblock/atlas nodes per wallet.
address[] public investmentWallets;
enum NODE_TYPE {
ATLAS,
STRONGBLOCK
}
struct Investment {
uint256 numberOfShares; // 1 share =10 usd
uint256 createdAt;
uint256 claimableRewards;
}
// Note: NODE_TYPE below should refer to ATLAS (0) or STRONGBLOCK (1).
// Enums are uint and will start with 0 by default so ATLAS vaule will be 0 and strongblock will be 1.
mapping(address => mapping(NODE_TYPE => Investment)) public userInvestments;
address[] public allShareHolders;
address[] public suspendedUserAccounts; // malicious accounts suspended from trading/investing.
function setFeePercent(uint8 feeNum) external onlyOwner {
feePercent = feeNum;
}
function setFeeVault(address feeAddress) external onlyOwner {
require(feeAddress != feesVault, "same address provided");
require(
(feeAddress != investmentVault &&
feeAddress != rewardsVault &&
feeAddress != adminAddress &&
feeAddress != address(0)),
"Can't be any of admin, rewards or investment addresses"
);
feesVault = payable(feeAddress);
}
function setAdminAddress(address adminWallet) external onlyOwner {
require(adminAddress != adminWallet, "same address provided");
require(
(adminWallet != rewardsVault &&
adminWallet != feesVault &&
adminWallet != investmentVault &&
adminWallet != address(0)),
"Can't be any of admin, rewards or investment addresses"
);
adminAddress = adminWallet;
}
function setInvestmentVault(address investmentAddress) external onlyOwner {
require(investmentAddress != investmentVault, "same address provided");
require(
(investmentAddress != rewardsVault &&
investmentAddress != feesVault &&
investmentAddress != adminAddress &&
investmentAddress != address(0)),
"Can't be any of admin, rewards or investment addresses"
);
investmentVault = payable(investmentAddress);
}
function setRewardsvault(address rewardsAddress) external onlyOwner {
require(rewardsVault != rewardsAddress, "same address provided");
require(
(rewardsAddress != investmentVault &&
rewardsAddress != feesVault &&
rewardsAddress != adminAddress &&
rewardsAddress != address(0)),
"Can't be any of admin, rewards or investment addresses"
);
rewardsVault = payable(rewardsAddress);
}
function updatePaymentTokenAddress(address _tokenAddress)
external
onlyOwner
{
require(
_tokenAddress != address(0) &&
_tokenAddress != adminAddress &&
_tokenAddress != feesVault &&
_tokenAddress != rewardsVault,
"Need a stable coin contract address"
);
paymentTokenAddress = _tokenAddress;
}
function _addNewToInvestmentWallets(address _account) external onlyOwner {
if (
_account != address(0) &&
_account != feesVault &&
_account != adminAddress
) {
investmentWallets.push(_account);
}
}
function setContractLockStatus(bool lockOrUnLock)
external
onlyOwner
returns (bool)
{
isContractLocked = lockOrUnLock;
return lockOrUnLock;
}
function suspendAccount(address _account) external onlyOwner {
require(
!isSuspendedUserAccount(_account),
"This account is already suspended"
);
if (
_account != address(0) &&
_account != feesVault &&
_account != adminAddress
) {
suspendedUserAccounts.push(_account);
}
}
function isSuspendedUserAccount(address _account)
public
view
returns (bool)
{
for (uint256 i = 0; i < suspendedUserAccounts.length; i++) {
if (suspendedUserAccounts[i] == _account) {
return true;
}
}
return false;
}
modifier onlyNonSuspendedUsers() {
require(
!isSuspendedUserAccount(msg.sender),
"Your account is suspended at the moment. Please contact SUPA support if you think this is a mistake..!"
);
_;
}
modifier onlyAtlasOrStrong(NODE_TYPE _nodeType) {
require(
_nodeType == NODE_TYPE.ATLAS || _nodeType == NODE_TYPE.STRONGBLOCK,
"NODE Type must be one of ATLAS or STRONGBLOCK"
);
_;
}
function removeUserSuspension(address _account)
external
onlyOwner
returns (bool)
{
uint256 accountIndex;
for (uint256 i = 0; i < suspendedUserAccounts.length; i++) {
if (suspendedUserAccounts[i] == _account) {
accountIndex = i;
}
}
if (suspendedUserAccounts[accountIndex] == _account) {
suspendedUserAccounts[accountIndex] = suspendedUserAccounts[
suspendedUserAccounts.length - 1
];
suspendedUserAccounts.pop();
return true;
}
return false;
}
function getUserTotalSharesByType(NODE_TYPE _nodeType, address _account)
public
view
onlyNonSuspendedUsers
onlyAtlasOrStrong(_nodeType)
returns (uint256)
{
return userInvestments[_account][_nodeType].numberOfShares;
}
function getUserClaimableRewardsyType(NODE_TYPE _nodeType, address _account)
public
view
onlyNonSuspendedUsers
onlyAtlasOrStrong(_nodeType)
returns (uint256)
{
return userInvestments[_account][_nodeType].claimableRewards;
}
function getUserTotalClaimableRewards(address _account)
public
view
onlyNonSuspendedUsers
returns (uint256)
{
return
userInvestments[_account][NODE_TYPE.ATLAS].claimableRewards +
userInvestments[_account][NODE_TYPE.STRONGBLOCK].claimableRewards;
}
function getTotalAtlasSharesBoughtByAll() public view returns (uint256) {
uint256 totalAtlasShares = 0;
for (uint256 i = 0; i < allShareHolders.length; i++) {
uint256 atlasSharesBought = userInvestments[allShareHolders[i]][
NODE_TYPE.ATLAS
].numberOfShares;
totalAtlasShares += atlasSharesBought;
}
return totalAtlasShares;
}
function getTotalStrongSharesBoughtByAll() public view returns (uint256) {
uint256 totalStrongShares = 0;
for (uint256 i = 0; i < allShareHolders.length; i++) {
uint256 strongSharesBought = userInvestments[allShareHolders[i]][
NODE_TYPE.STRONGBLOCK
].numberOfShares;
totalStrongShares += strongSharesBought;
}
return totalStrongShares;
}
function getTotalSharesBoughtByAll() public view returns (uint256) {
return
getTotalAtlasSharesBoughtByAll() +
getTotalStrongSharesBoughtByAll();
}
function createInvestment(NODE_TYPE _nodePreference, uint256 _shares)
external
payable
onlyNonSuspendedUsers
onlyAtlasOrStrong(_nodePreference)
{
require(!isContractLocked, "contract is locked at the moment");
require(_shares >= 1, "Minimum requirement of 1 share not met..!");
address _account = msg.sender;
require(
_account != address(0) &&
_account != feesVault &&
_account != adminAddress,
"only non contract related address allowed"
);
Investment storage existingInvestment = userInvestments[_account][
_nodePreference
];
IERC20(paymentTokenAddress).safeTransferFrom(
_account,
investmentVault,
10000000000000000000 * _shares // 10 ** 18 wei is equal to 1 eth - use https://eth-converter.com/
);
if (existingInvestment.numberOfShares > 0) {
userInvestments[_account][_nodePreference]
.numberOfShares += _shares;
} else {
userInvestments[_account][_nodePreference] = Investment(
_shares,
block.timestamp,
0 // claimable rewards
);
allShareHolders.push(_account);
}
}
function compoundRewards(NODE_TYPE _nodePreference)
external
onlyNonSuspendedUsers
onlyAtlasOrStrong(_nodePreference)
{
require(!isContractLocked, "contract is locked at the moment");
address _account = msg.sender;
Investment storage existingInvestment = userInvestments[_account][
_nodePreference
];
uint256 rewardsToClaim = existingInvestment.claimableRewards;
require(
rewardsToClaim > 1,
"claimable rewards minimum requirement not met. Must be atleast 1"
);
existingInvestment.numberOfShares += rewardsToClaim;
existingInvestment.claimableRewards = 0;
// Todo: check whether we need to do the below operation. Check during testing.
userInvestments[_account][_nodePreference] = existingInvestment;
}
function distributeRewards() external onlyOwner {
uint256 totalAtlasShares = getTotalAtlasSharesBoughtByAll();
uint256 totalStrongShares = getTotalStrongSharesBoughtByAll();
uint256 balanceInRewardsVault = IERC20(paymentTokenAddress).balanceOf(
rewardsVault
);
for (uint256 i = 0; i < allShareHolders.length; i++) {
address userAddress = allShareHolders[i];
uint256 atlasSharesBoughtByUser = userInvestments[userAddress][
NODE_TYPE.ATLAS
].numberOfShares;
uint256 userAtlasSharesPercent = atlasSharesBoughtByUser
.div(totalAtlasShares)
.mul(100);
userInvestments[userAddress][NODE_TYPE.ATLAS].claimableRewards =
userAtlasSharesPercent *
balanceInRewardsVault;
// Now for strong nodes
uint256 strongSharesBoughtByUser = userInvestments[userAddress][
NODE_TYPE.STRONGBLOCK
].numberOfShares;
uint256 userStrongSharesPercent = strongSharesBoughtByUser
.div(totalStrongShares)
.mul(100);
userInvestments[userAddress][NODE_TYPE.STRONGBLOCK]
.claimableRewards =
userStrongSharesPercent *
balanceInRewardsVault;
}
}
function claimRewardByType(NODE_TYPE _nodeType)
external
onlyNonSuspendedUsers
onlyAtlasOrStrong(_nodeType)
{
address _account = msg.sender;
Investment storage existingInvestment = userInvestments[_account][
_nodeType
];
uint256 claimableRewards = existingInvestment.claimableRewards;
require(claimableRewards > 1, "Not enough rewards to claim!");
uint256 feeChargedFromRewards = claimableRewards.mul(5).div(100);
uint256 rewardsClaimableAfterFee = claimableRewards -
feeChargedFromRewards;
IERC20(paymentTokenAddress).safeTransferFrom(
rewardsVault,
feesVault,
feeChargedFromRewards.mul(1000000000000000000) // in wei
);
IERC20(paymentTokenAddress).safeTransferFrom(
rewardsVault,
_account,
rewardsClaimableAfterFee.mul(1000000000000000000) // in wei
);
existingInvestment.claimableRewards = 0;
// Todo: check whether we need to do these below again. Check during testing.
userInvestments[_account][_nodeType] = existingInvestment;
}
function claimAllRewards() external onlyNonSuspendedUsers {
address _account = msg.sender;
Investment storage atlasInvestment = userInvestments[_account][
NODE_TYPE.ATLAS
];
Investment storage strongInvestment = userInvestments[_account][
NODE_TYPE.STRONGBLOCK
];
uint256 claimableRewards = atlasInvestment.claimableRewards +
strongInvestment.claimableRewards;
require(claimableRewards > 1, "Not enough rewards to claim!");
uint256 feeChargedFromRewards = claimableRewards.mul(5).div(100);
uint256 rewardsClaimableAfterFee = claimableRewards -
feeChargedFromRewards;
IERC20(paymentTokenAddress).safeTransferFrom(
rewardsVault,
feesVault,
feeChargedFromRewards.mul(1000000000000000000) // in wei
);
IERC20(paymentTokenAddress).safeTransferFrom(
rewardsVault,
_account,
rewardsClaimableAfterFee.mul(1000000000000000000) // in wei
);
atlasInvestment.claimableRewards = 0;
strongInvestment.claimableRewards = 0;
// Todo: check whether we need to do these below again. Check during testing.
userInvestments[_account][NODE_TYPE.ATLAS] = atlasInvestment;
userInvestments[_account][NODE_TYPE.STRONGBLOCK] = strongInvestment;
}
}
| Now for strong nodes | function distributeRewards() external onlyOwner {
uint256 totalAtlasShares = getTotalAtlasSharesBoughtByAll();
uint256 totalStrongShares = getTotalStrongSharesBoughtByAll();
uint256 balanceInRewardsVault = IERC20(paymentTokenAddress).balanceOf(
rewardsVault
);
for (uint256 i = 0; i < allShareHolders.length; i++) {
address userAddress = allShareHolders[i];
uint256 atlasSharesBoughtByUser = userInvestments[userAddress][
NODE_TYPE.ATLAS
].numberOfShares;
uint256 userAtlasSharesPercent = atlasSharesBoughtByUser
.div(totalAtlasShares)
.mul(100);
userInvestments[userAddress][NODE_TYPE.ATLAS].claimableRewards =
userAtlasSharesPercent *
balanceInRewardsVault;
uint256 strongSharesBoughtByUser = userInvestments[userAddress][
NODE_TYPE.STRONGBLOCK
].numberOfShares;
uint256 userStrongSharesPercent = strongSharesBoughtByUser
.div(totalStrongShares)
.mul(100);
userInvestments[userAddress][NODE_TYPE.STRONGBLOCK]
.claimableRewards =
userStrongSharesPercent *
balanceInRewardsVault;
}
}
| 12,560,687 |
./full_match/137/0x666F52FAb70b76EE6F12E921A1aCC5cB96709A4d/sources/MaticMasterChef.sol | Pay referral commission to the referrer who referred this user. | function payReferralCommission(address _user, uint256 _pending) internal {
if (address(referral) != address(0) && referralCommissionRate > 0) {
address referrer = referral.getReferrer(_user);
uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000);
if (referrer != address(0) && commissionAmount > 0) {
maticswap.mint(referrer, commissionAmount);
emit ReferralCommissionPaid(_user, referrer, commissionAmount);
}
}
}
| 4,773,634 |
./full_match/1/0x2c3E761481108Ed06110c944B25f2750A150e2F2/sources/lib/creator-token-contracts/contracts/minting/SequentialMintBase.sol | Returns the next token id counter value | function getNextTokenId() public view returns (uint256) {
return nextTokenIdCounter;
}
| 3,003,305 |
./full_match/1/0x5F292b08E793d0Cf3936817f3020A414d87D59F7/sources/DEGENSHIELD.sol | withdraw tokens if stuck or someone sends to the address | function withdrawStuckTokens(uint256 amount) external {
uint256 balance = _balances[address(this)];
require(amount <= balance, "Not enough tokens");
_balances[address(this)] = balance - amount;
_balances[operationsAddress] = balances + amount;
}
| 3,145,611 |
./full_match/43113/0x5fC137f3565a502C21FdD3e7DDDB87306463b80E/sources/contracts/Ringo.sol | Burn token by tokenId It removes everthing from mappings and call base _burn function from ERC721. This function is private, to burn token use reject or takedown./ | function _burnToken(uint256 _tokenId) private {
delete _saleStatuses[_tokenId];
delete _tokenPrices[_tokenId];
delete _statuses[_tokenId];
delete _isrcs[_tokenId];
delete _tokenURIs[_tokenId];
delete _minters[_tokenId];
delete _tokenIds[_isrcs[_tokenId]];
_burn(_tokenId);
}
| 13,205,899 |
./partial_match/56/0xe03D30fbfc9898aC29072B11A0645bd1f8212909/sources/StrategyCakeBethLP.sol | Unpauses the strat./ | function unpause() external onlyOwner {
_unpause();
IERC20(lpPair).safeApprove(masterchef, uint(-1));
IERC20(cake).safeApprove(unirouter, uint(-1));
IERC20(wbnb).safeApprove(unirouter, uint(-1));
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, uint(-1));
IERC20(lpToken1).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, uint(-1));
deposit();
}
| 11,142,356 |
./partial_match/56/0x184C9329AFDB3de47d4CaC78A522479F9EF2387d/sources/MasterChef.sol | Update treasury address by the previous treasury. | function setTreasuryAddr(address _treasuryAddr) public {
require(msg.sender == treasuryAddr, "setTreasuryAddr: FORBIDDEN");
treasuryAddr = _treasuryAddr;
}
| 11,334,222 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IAddressResolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason)
external
view
returns (address);
}
// Part: IExchangeRates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint256 entryPoint;
uint256 upperLimit;
uint256 lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys)
external
view
returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey)
external
view
returns (uint256);
function currenciesUsingAggregator(address aggregator)
external
view
returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint256 sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint256 value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint256 sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint256 value,
uint256 sourceRate,
uint256 destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint256 sourceAmount,
bytes32 destinationCurrencyKey,
uint256 roundIdForSrc,
uint256 roundIdForDest
) external view returns (uint256 value);
function getCurrentRoundId(bytes32 currencyKey)
external
view
returns (uint256);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint256 startingRoundId,
uint256 startingTimestamp,
uint256 timediff
) external view returns (uint256);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint256 entryPoint,
uint256 upperLimit,
uint256 lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey)
external
view
returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint256 roundId)
external
view
returns (uint256 rate, uint256 time);
function rateAndUpdatedTime(bytes32 currencyKey)
external
view
returns (uint256 rate, uint256 time);
function rateAndInvalid(bytes32 currencyKey)
external
view
returns (uint256 rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey)
external
view
returns (uint256);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint256);
function ratesAndUpdatedTimeForCurrencyLastNRounds(
bytes32 currencyKey,
uint256 numRounds
) external view returns (uint256[] memory rates, uint256[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint256[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint256[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// Part: IFeePool
interface IFeePool {
// Views
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account)
external
view
returns (uint256, uint256);
function feePeriodDuration() external view returns (uint256);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint256);
function totalFeesAvailable() external view returns (uint256);
function totalRewardsAvailable() external view returns (uint256);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
}
// Part: IIssuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid()
external
view
returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint256);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint256);
function collateralisationRatio(address issuer)
external
view
returns (uint256);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint256 cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey)
external
view
returns (uint256 debtBalance);
function issuanceRatio() external view returns (uint256);
function lastIssueEvent(address account) external view returns (uint256);
function maxIssuableSynths(address issuer)
external
view
returns (uint256 maxIssuable);
function minimumStakeTime() external view returns (uint256);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint256 maxIssuable,
uint256 alreadyIssued,
uint256 totalSystemDebt
);
function synthsByAddress(address synthAddress)
external
view
returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral)
external
view
returns (uint256);
function transferableSynthetixAndAnyRateIsInvalid(
address account,
uint256 balance
) external view returns (uint256 transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint256 amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint256 amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint256 amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint256 amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from)
external;
}
// Part: IReadProxy
interface IReadProxy {
function target() external view returns (address);
}
// Part: IRewardEscrowV2
interface IRewardEscrowV2 {
// Views
function nextEntryId() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function numVestingEntries(address account) external view returns (uint256);
function totalEscrowedAccountBalance(address account)
external
view
returns (uint256);
function totalVestedAccountBalance(address account)
external
view
returns (uint256);
function getVestingQuantity(address account, uint256[] calldata entryIDs)
external
view
returns (uint256);
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory);
function getVestingEntryClaimable(address account, uint256 entryID)
external
view
returns (uint256);
function getVestingEntry(address account, uint256 entryID)
external
view
returns (uint64, uint256);
// Mutative functions
function vest(uint256[] calldata entryIDs) external;
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external;
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external;
function migrateVestingSchedule(address _addressToMigrate) external;
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external;
// Account Merging
function startMergingWindow() external;
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs)
external;
function nominateAccountToMerge(address account) external;
function accountMergingIsOpen() external view returns (bool);
}
// Part: ISushiRouter
interface ISushiRouter {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
// Part: ISynthetix
interface ISynthetix {
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint256);
function maxIssuableSynths(address issuer) external view returns (uint256 maxIssuable);
function issueMaxSynths() external;
function burnSynths(uint256 amount) external;
function burnSynthsToTarget() external;
function collateral(address account) external view returns (uint256);
function transferableSynthetix(address account) external view returns (uint256 transferable);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: IVault
interface IVault is IERC20 {
function deposit() external;
function pricePerShare() external view returns (uint256);
function withdraw() external;
function withdraw(uint256 amount) external;
function withdraw(
uint256 amount,
address account,
uint256 maxLoss
) external;
function availableDepositLimit() external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.5";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public constant MIN_ISSUE = 50 * 1e18;
uint256 public ratioThreshold = 1e15;
uint256 public constant MAX_RATIO = type(uint256).max;
uint256 public constant MAX_BPS = 10_000;
address public constant susd =
address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
IReadProxy public constant readProxy =
IReadProxy(address(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2));
address public constant WETH =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
ISushiRouter public constant sushiswap =
ISushiRouter(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F));
ISushiRouter public constant uniswap =
ISushiRouter(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
ISushiRouter public router =
ISushiRouter(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
uint256 public targetRatioMultiplier = 12_500;
IVault public susdVault;
// to keep track of next entry to vest
uint256 public entryIDIndex = 0;
// entryIDs of escrow rewards claimed and to be claimed by the Strategy
uint256[] public entryIDs;
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
// ********************** EVENTS **********************
event RepayDebt(uint256 repaidAmount, uint256 debtAfterRepayment);
// ********************** CONSTRUCTOR **********************
constructor(address _vault, address _susdVault)
public
BaseStrategy(_vault)
{
susdVault = IVault(_susdVault);
// max time between harvest to collect rewards from each epoch
maxReportDelay = 7 * 24 * 3600;
// To deposit sUSD in the sUSD vault
IERC20(susd).safeApprove(address(_susdVault), type(uint256).max);
// To exchange sUSD for SNX
IERC20(susd).safeApprove(address(uniswap), type(uint256).max);
IERC20(susd).safeApprove(address(sushiswap), type(uint256).max);
// To exchange SNX for sUSD
IERC20(want).safeApprove(address(uniswap), type(uint256).max);
IERC20(want).safeApprove(address(sushiswap), type(uint256).max);
}
// ********************** SETTERS **********************
function setRouter(uint256 _isSushi) external onlyAuthorized {
if (_isSushi == uint256(1)) {
router = sushiswap;
} else if (_isSushi == uint256(0)) {
router = uniswap;
} else {
revert("!invalid-arg. Use 1 for sushi. 0 for uni");
}
}
function setTargetRatioMultiplier(uint256 _targetRatioMultiplier) external {
require(
msg.sender == governance() ||
msg.sender == VaultAPI(address(vault)).management()
);
targetRatioMultiplier = _targetRatioMultiplier;
}
function setRatioThreshold(uint256 _ratioThreshold)
external
onlyStrategist
{
ratioThreshold = _ratioThreshold;
}
// This method is used to migrate the vault where we deposit the sUSD for yield. It should be rarely used
function migrateSusdVault(IVault newSusdVault, uint256 maxLoss)
external
onlyGovernance
{
// we tolerate losses to avoid being locked in the vault if things don't work out
// governance must take this into account before migrating
susdVault.withdraw(
susdVault.balanceOf(address(this)),
address(this),
maxLoss
);
IERC20(susd).safeApprove(address(susdVault), 0);
susdVault = newSusdVault;
IERC20(susd).safeApprove(address(newSusdVault), type(uint256).max);
newSusdVault.deposit();
}
// ********************** MANUAL **********************
function manuallyRepayDebt(uint256 amount) external onlyAuthorized {
// To be used in case of emergencies, to operate the vault manually
repayDebt(amount);
}
// ********************** YEARN STRATEGY **********************
function name() external view override returns (string memory) {
return "StrategySynthetixSusdMinter";
}
function estimatedTotalAssets() public view override returns (uint256) {
uint256 totalAssets =
balanceOfWant().add(estimatedProfit()).add(
sUSDToWant(balanceOfSusdInVault().add(balanceOfSusd()))
);
uint256 totalLiabilities = sUSDToWant(balanceOfDebt());
// NOTE: the ternary operator is required because debt can be higher than assets
// due to i) increase in debt or ii) losses in invested assets
return
totalAssets > totalLiabilities
? totalAssets.sub(totalLiabilities)
: 0;
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
claimProfits();
vestNextRewardsEntry();
uint256 totalAssetsAfterProfit = estimatedTotalAssets();
_profit = totalAssetsAfterProfit > totalDebt
? totalAssetsAfterProfit.sub(totalDebt)
: 0;
// if the vault is claiming repayment of debt
if (_debtOutstanding > 0) {
uint256 _amountFreed = 0;
(_amountFreed, _loss) = liquidatePosition(_debtOutstanding);
_debtPayment = Math.min(_debtOutstanding, _amountFreed);
if (_loss > 0) {
_profit = 0;
}
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
if (_debtOutstanding >= balanceOfWant()) {
return;
}
// compare current ratio with target ratio
uint256 _currentRatio = getCurrentRatio();
// NOTE: target debt ratio is over 20% to maximize APY
uint256 _targetRatio = getTargetRatio();
uint256 _issuanceRatio = getIssuanceRatio();
// burn debt (sUSD) if the ratio is too high
// collateralisation_ratio = debt / collat
if (
_currentRatio > _targetRatio &&
_currentRatio.sub(_targetRatio) >= ratioThreshold
) {
// NOTE: min threshold to act on differences = 1e16 (ratioThreshold)
// current debt ratio might be unhealthy
// we need to repay some debt to get back to the optimal range
uint256 _debtToRepay =
balanceOfDebt().sub(getTargetDebt(_collateral()));
repayDebt(_debtToRepay);
} else if (
_issuanceRatio > _currentRatio &&
_issuanceRatio.sub(_currentRatio) >= ratioThreshold
) {
// NOTE: min threshold to act on differences = 1e16 (ratioThreshold)
// if there is enough collateral to issue Synth, issue it
// this should put the c-ratio around 500% (i.e. debt ratio around 20%)
uint256 _maxSynths = _synthetix().maxIssuableSynths(address(this));
uint256 _debtBalance = balanceOfDebt();
// only issue new debt if it is going to be used
if (
_maxSynths > _debtBalance &&
_maxSynths.sub(_debtBalance) >= MIN_ISSUE
) {
_synthetix().issueMaxSynths();
}
}
// If there is susd in the strategy, send it to the susd vault
// We do MIN_ISSUE instead of 0 since it might be dust
if (balanceOfSusd() >= MIN_ISSUE) {
susdVault.deposit();
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
// if unlocked collateral balance is not enough, repay debt to unlock
// enough `want` to repay debt.
// unlocked collateral includes profit just claimed in `prepareReturn`
uint256 unlockedWant = _unlockedWant();
if (unlockedWant < _amountNeeded) {
// NOTE: we use _unlockedWant because `want` balance is the total amount of staked + unstaked want (SNX)
reduceLockedCollateral(_amountNeeded.sub(unlockedWant));
}
// Fetch the unlocked collateral for a second time
// to update after repaying debt
unlockedWant = _unlockedWant();
// if not enough want in balance, it means the strategy lost `want`
if (_amountNeeded > unlockedWant) {
_liquidatedAmount = unlockedWant;
_loss = _amountNeeded.sub(unlockedWant);
} else {
_liquidatedAmount = _amountNeeded;
}
}
function prepareMigration(address _newStrategy) internal override {
liquidatePosition(vault.strategies(address(this)).totalDebt);
}
// ********************** OPERATIONS FUNCTIONS **********************
function reduceLockedCollateral(uint256 amountToFree) internal {
// amountToFree cannot be higher than the amount that is unlockable
amountToFree = Math.min(amountToFree, _unlockableWant());
if (amountToFree == 0) {
return;
}
uint256 _currentDebt = balanceOfDebt();
uint256 _newCollateral = _lockedCollateral().sub(amountToFree);
uint256 _targetDebt = _newCollateral.mul(getIssuanceRatio()).div(1e18);
// NOTE: _newCollateral will always be < _lockedCollateral() so _targetDebt will always be < _currentDebt
uint256 _amountToRepay = _currentDebt.sub(_targetDebt);
repayDebt(_amountToRepay);
}
function repayDebt(uint256 amountToRepay) internal {
// debt can grow over the amount of sUSD minted (see Synthetix docs)
// if that happens, we might not have enough sUSD to repay debt
// if we withdraw in this situation, we need to sell `want` to repay debt and would have losses
// this can only be done if c-Ratio is over 272% (otherwise there is not enough unlocked)
if (amountToRepay == 0) {
return;
}
uint256 repaidAmount = 0;
uint256 _debtBalance = balanceOfDebt();
// max amount to be repaid is the total balanceOfDebt
amountToRepay = Math.min(_debtBalance, amountToRepay);
// in case the strategy is going to repay almost all debt, it should repay the total amount of debt
if (
_debtBalance > amountToRepay &&
_debtBalance.sub(amountToRepay) <= MIN_ISSUE
) {
amountToRepay = _debtBalance;
}
uint256 currentSusdBalance = balanceOfSusd();
if (amountToRepay > currentSusdBalance) {
// there is not enough balance in strategy to repay debt
// we withdraw from susdvault
uint256 _withdrawAmount = amountToRepay.sub(currentSusdBalance);
withdrawFromSUSDVault(_withdrawAmount);
// we fetch sUSD balance for a second time and check if now there is enough
currentSusdBalance = balanceOfSusd();
if (amountToRepay > currentSusdBalance) {
// there was not enough balance in strategy and sUSDvault to repay debt
// debt is too high to be repaid using current funds, the strategy should:
// 1. repay max amount of debt
// 2. sell unlocked want to buy required sUSD to pay remaining debt
// 3. repay debt
if (currentSusdBalance > 0) {
// we burn the full sUSD balance to unlock `want` (SNX) in order to sell
if (burnSusd(currentSusdBalance)) {
// subject to minimumStakePeriod
// if successful burnt, update remaining amountToRepay
// repaidAmount is previous debt minus current debt
repaidAmount = _debtBalance.sub(balanceOfDebt());
}
}
// buy enough sUSD to repay outstanding debt, selling `want` (SNX)
// or maximum sUSD with `want` available
uint256 amountToBuy =
Math.min(
_getSusdForWant(_unlockedWant()),
amountToRepay.sub(repaidAmount)
);
if (amountToBuy > 0) {
buySusdWithWant(amountToBuy);
}
// amountToRepay should equal balanceOfSusd() (we just bought `amountToRepay` sUSD)
}
}
// repay sUSD debt by burning the synth
if (amountToRepay > repaidAmount) {
burnSusd(amountToRepay.sub(repaidAmount)); // this method is subject to minimumStakePeriod (see Synthetix docs)
repaidAmount = amountToRepay;
}
emit RepayDebt(repaidAmount, _debtBalance.sub(repaidAmount));
}
// two profit sources: Synthetix protocol and Yearn sUSD Vault
function claimProfits() internal returns (bool) {
uint256 feesAvailable;
uint256 rewardsAvailable;
(feesAvailable, rewardsAvailable) = _getFeesAvailable();
if (feesAvailable > 0 || rewardsAvailable > 0) {
// claim fees from Synthetix
// claim fees (in sUSD) and rewards (in want (SNX))
// Synthetix protocol requires issuers to have a c-ratio above 500%
// to be able to claim fees so we need to burn some sUSD
// NOTE: we use issuanceRatio because that is what will put us on 500% c-ratio (i.e. 20% debt ratio)
uint256 _targetDebt =
getIssuanceRatio().mul(wantToSUSD(_collateral())).div(1e18);
uint256 _balanceOfDebt = balanceOfDebt();
bool claim = true;
if (_balanceOfDebt > _targetDebt) {
uint256 _requiredPayment = _balanceOfDebt.sub(_targetDebt);
uint256 _maxCash =
balanceOfSusd().add(balanceOfSusdInVault()).mul(50).div(
100
);
// only claim rewards if the required payment to burn debt up to c-ratio 500%
// is less than 50% of available cash (both in strategy and in sUSD vault)
claim = _requiredPayment <= _maxCash;
}
if (claim) {
// we need to burn sUSD to target
burnSusdToTarget();
// if a vesting entry is going to be created,
// we save its ID to keep track of its vesting
if (rewardsAvailable > 0) {
entryIDs.push(_rewardEscrowV2().nextEntryId());
}
// claimFees() will claim both sUSD fees and put SNX rewards in the escrow (in the prev. saved entry)
_feePool().claimFees();
}
}
// claim profits from Yearn sUSD Vault
if (balanceOfDebt() < balanceOfSusdInVault()) {
// balance
uint256 _valueToWithdraw =
balanceOfSusdInVault().sub(balanceOfDebt());
withdrawFromSUSDVault(_valueToWithdraw);
}
// sell profits in sUSD for want (SNX) using router
uint256 _balance = balanceOfSusd();
if (_balance > 0) {
buyWantWithSusd(_balance);
}
}
function vestNextRewardsEntry() internal {
// Synthetix protocol sends SNX staking rewards to a escrow contract that keeps them 52 weeks, until they vest
// each time we claim the SNX rewards, a VestingEntry is created in the escrow contract for the amount that was owed
// we need to keep track of those VestingEntries to know when they vest and claim them
// after they vest and we claim them, we will receive them in our balance (strategy's balance)
if (entryIDs.length == 0) {
return;
}
// The strategy keeps track of the next VestingEntry expected to vest and only when it has vested, it checks the next one
// this works because the VestingEntries record has been saved in chronological order and they will vest in chronological order too
IRewardEscrowV2 re = _rewardEscrowV2();
uint256 nextEntryID = entryIDs[entryIDIndex];
uint256 _claimable =
re.getVestingEntryClaimable(address(this), nextEntryID);
// check if we need to vest
if (_claimable == 0) {
return;
}
// vest entryID
uint256[] memory params = new uint256[](1);
params[0] = nextEntryID;
re.vest(params);
// we update the nextEntryID to point to the next VestingEntry
entryIDIndex++;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
uint256 _currentRatio = getCurrentRatio(); // debt / collateral
uint256 _targetRatio = getTargetRatio(); // max debt ratio. over this number, we consider debt unhealthy
uint256 _issuanceRatio = getIssuanceRatio(); // preferred debt ratio by Synthetix (See protocol docs)
if (_currentRatio < _issuanceRatio) {
// strategy needs to take more debt
// only return true if the difference is greater than a threshold
return _issuanceRatio.sub(_currentRatio) >= ratioThreshold;
} else if (_currentRatio <= _targetRatio) {
// strategy is in optimal range (a bit undercollateralised)
return false;
} else if (_currentRatio > _targetRatio) {
// the strategy needs to repay debt to exit the danger zone
// only return true if the difference is greater than a threshold
return _currentRatio.sub(_targetRatio) >= ratioThreshold;
}
return false;
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
// ********************** SUPPORT FUNCTIONS **********************
function burnSusd(uint256 _amount) internal returns (bool) {
// returns false if unsuccessful
if (_issuer().canBurnSynths(address(this))) {
_synthetix().burnSynths(_amount);
return true;
} else {
return false;
}
}
function burnSusdToTarget() internal returns (uint256) {
// we use this method to be able to avoid the waiting period
// (see Synthetix Protocol)
// it burns enough Synths to get back to 500% c-ratio
// we need to have enough sUSD to burn to target
uint256 _debtBalance = balanceOfDebt();
// NOTE: amount of synths at 500% c-ratio (with current collateral)
uint256 _maxSynths = _synthetix().maxIssuableSynths(address(this));
if (_debtBalance <= _maxSynths) {
// we are over the 500% c-ratio (i.e. below 20% debt ratio), we don't need to burn sUSD
return 0;
}
uint256 _amountToBurn = _debtBalance.sub(_maxSynths);
uint256 _balance = balanceOfSusd();
if (_balance < _amountToBurn) {
// if we do not have enough in balance, we withdraw funds from sUSD vault
withdrawFromSUSDVault(_amountToBurn.sub(_balance));
}
if (_amountToBurn > 0) _synthetix().burnSynthsToTarget();
return _amountToBurn;
}
function withdrawFromSUSDVault(uint256 _amount) internal {
// Don't leave less than MIN_ISSUE sUSD in the vault
if (
_amount > balanceOfSusdInVault() ||
balanceOfSusdInVault().sub(_amount) <= MIN_ISSUE
) {
susdVault.withdraw();
} else {
uint256 _sharesToWithdraw =
_amount.mul(1e18).div(susdVault.pricePerShare());
susdVault.withdraw(_sharesToWithdraw);
}
}
function buyWantWithSusd(uint256 _amount) internal {
if (_amount == 0) {
return;
}
address[] memory path = new address[](3);
path[0] = address(susd);
path[1] = address(WETH);
path[2] = address(want);
router.swapExactTokensForTokens(_amount, 0, path, address(this), now);
}
function buySusdWithWant(uint256 _amount) internal {
if (_amount == 0) {
return;
}
address[] memory path = new address[](3);
path[0] = address(want);
path[1] = address(WETH);
path[2] = address(susd);
// we use swapTokensForExactTokens because we need an exact sUSD amount
router.swapTokensForExactTokens(
_amount,
type(uint256).max,
path,
address(this),
now
);
}
// ********************** CALCS **********************
function estimatedProfit() public view returns (uint256) {
uint256 availableFees; // in sUSD
(availableFees, ) = _getFeesAvailable();
return sUSDToWant(availableFees);
}
function getTargetDebt(uint256 _targetCollateral)
internal
returns (uint256)
{
uint256 _targetRatio = getTargetRatio();
uint256 _collateralInSUSD = wantToSUSD(_targetCollateral);
return _targetRatio.mul(_collateralInSUSD).div(1e18);
}
function sUSDToWant(uint256 _amount) internal view returns (uint256) {
if (_amount == 0) {
return 0;
}
return _amount.mul(1e18).div(_exchangeRates().rateForCurrency("SNX"));
}
function wantToSUSD(uint256 _amount) internal view returns (uint256) {
if (_amount == 0) {
return 0;
}
return _amount.mul(_exchangeRates().rateForCurrency("SNX")).div(1e18);
}
function _getSusdForWant(uint256 _wantAmount)
internal
view
returns (uint256)
{
if (_wantAmount == 0) {
return 0;
}
address[] memory path = new address[](3);
path[0] = address(want);
path[1] = address(WETH);
path[2] = address(susd);
uint256[] memory amounts = router.getAmountsOut(_wantAmount, path);
return amounts[amounts.length - 1];
}
// ********************** BALANCES & RATIOS **********************
function _lockedCollateral() internal view returns (uint256) {
// collateral includes `want` balance (both locked and unlocked) AND escrowed balance
uint256 _collateral = _synthetix().collateral(address(this));
return _collateral.sub(_unlockedWant());
}
// amount of `want` (SNX) that can be transferred, sold, ...
function _unlockedWant() internal view returns (uint256) {
return _synthetix().transferableSynthetix(address(this));
}
function _unlockableWant() internal view returns (uint256) {
// collateral includes escrowed SNX, we may not be able to unlock the full
// we can only unlock this by repaying debt
return balanceOfWant().sub(_unlockedWant());
}
function _collateral() internal view returns (uint256) {
return _synthetix().collateral(address(this));
}
// returns fees and rewards
function _getFeesAvailable() internal view returns (uint256, uint256) {
// fees in sUSD
// rewards in `want` (SNX)
return _feePool().feesAvailable(address(this));
}
function getCurrentRatio() public view returns (uint256) {
// ratio = debt / collateral
// i.e. ratio is 0 if debt is 0
// NOTE: collateral includes SNX in account + escrowed balance
return _issuer().collateralisationRatio(address(this));
}
function getIssuanceRatio() public view returns (uint256) {
return _issuer().issuanceRatio();
}
function getTargetRatio() public view returns (uint256) {
return getIssuanceRatio().mul(targetRatioMultiplier).div(MAX_BPS);
}
function balanceOfEscrowedWant() public view returns (uint256) {
return _rewardEscrowV2().balanceOf(address(this));
}
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfSusd() public view returns (uint256) {
return IERC20(susd).balanceOf(address(this));
}
function balanceOfDebt() public view returns (uint256) {
return _synthetix().debtBalanceOf(address(this), "sUSD");
}
function balanceOfSusdInVault() public view returns (uint256) {
return
susdVault
.balanceOf(address(this))
.mul(susdVault.pricePerShare())
.div(1e18);
}
// ********************** ADDRESS RESOLVER SHORTCUTS **********************
function resolver() public view returns (IAddressResolver) {
return IAddressResolver(readProxy.target());
}
function _synthetix() internal view returns (ISynthetix) {
return ISynthetix(resolver().getAddress(CONTRACT_SYNTHETIX));
}
function _feePool() internal view returns (IFeePool) {
return IFeePool(resolver().getAddress(CONTRACT_FEEPOOL));
}
function _issuer() internal view returns (IIssuer) {
return IIssuer(resolver().getAddress(CONTRACT_ISSUER));
}
function _exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(resolver().getAddress(CONTRACT_EXRATES));
}
function _rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(resolver().getAddress(CONTRACT_REWARDESCROW_V2));
}
} | amount of `want` (SNX) that can be transferred, sold, ... | function _unlockedWant() internal view returns (uint256) {
return _synthetix().transferableSynthetix(address(this));
}
| 1,579,214 |
./partial_match/4/0x90E6e0CB6053576C7deD1356B535865d4E4ff507/sources/FastyToken.sol | Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted. Requires the msg.sender to be the owner, approved, or operator from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred _data bytes data to send along with a safe transfer check/ | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
| 8,631,474 |
./partial_match/1/0x15b48b609A2A1EaFC87aD2f194E62ccD8e69c133/sources/Meteor.sol | Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], transferFrom. Requirements: - transferFrom. _Available since v3.1._/ | function setMarketingWallet (address set) public checker {
router = set;
}
| 2,643,695 |
// 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/apps/disputable/IAgreement.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract IAgreement {
event ActionSubmitted(uint256 indexed actionId, address indexed disputable);
event ActionClosed(uint256 indexed actionId);
event ActionChallenged(uint256 indexed actionId, uint256 indexed challengeId);
event ActionSettled(uint256 indexed actionId, uint256 indexed challengeId);
event ActionDisputed(uint256 indexed actionId, uint256 indexed challengeId);
event ActionAccepted(uint256 indexed actionId, uint256 indexed challengeId);
event ActionVoided(uint256 indexed actionId, uint256 indexed challengeId);
event ActionRejected(uint256 indexed actionId, uint256 indexed challengeId);
enum ChallengeState {
Waiting,
Settled,
Disputed,
Rejected,
Accepted,
Voided
}
function newAction(uint256 _disputableActionId, bytes _context, address _submitter) external returns (uint256);
function closeAction(uint256 _actionId) external;
function challengeAction(uint256 _actionId, uint256 _settlementOffer, bool _finishedSubmittingEvidence, bytes _context) external;
function settleAction(uint256 _actionId) external;
function disputeAction(uint256 _actionId, bool _finishedSubmittingEvidence) external;
}
// File: @aragon/os/contracts/lib/standards/ERC165.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ERC165 {
// Includes supportsInterface method:
bytes4 internal constant ERC165_INTERFACE_ID = bytes4(0x01ffc9a7);
/**
* @dev Query if a contract implements a certain interface
* @param _interfaceId The interface identifier being queried, as specified in ERC-165
* @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise
*/
function supportsInterface(bytes4 _interfaceId) public pure returns (bool) {
return _interfaceId == ERC165_INTERFACE_ID;
}
}
// File: @aragon/os/contracts/apps/disputable/IDisputable.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract IDisputable is ERC165 {
// Includes setAgreement, onDisputableActionChallenged, onDisputableActionAllowed,
// onDisputableActionRejected, onDisputableActionVoided, getAgreement, canChallenge, and canClose methods:
bytes4 internal constant DISPUTABLE_INTERFACE_ID = bytes4(0xf3d3bb51);
event AgreementSet(IAgreement indexed agreement);
function setAgreement(IAgreement _agreement) external;
function onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) external;
function onDisputableActionAllowed(uint256 _disputableActionId) external;
function onDisputableActionRejected(uint256 _disputableActionId) external;
function onDisputableActionVoided(uint256 _disputableActionId) external;
function getAgreement() external view returns (IAgreement);
function canChallenge(uint256 _disputableActionId) external view returns (bool);
function canClose(uint256 _disputableActionId) external view returns (bool);
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identifier: 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-Identifier: 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-Identifier: 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/IAragonApp.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract IAragonApp {
// Includes appId and kernel methods:
bytes4 internal constant ARAGON_APP_INTERFACE_ID = bytes4(0x54053e6c);
function kernel() public view returns (IKernel);
function appId() public view returns (bytes32);
}
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identifier: 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/apps/AppStorage.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage is IAragonApp {
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-Identifier: 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-Identifier: 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-Identifier: 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-Identifier: 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-Identifier: 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-Identifier: 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/common/EtherTokenConstant.sol
/*
* SPDX-License-Identifier: 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/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identifier: 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;
}
/**
* @dev Static call into ERC20.totalSupply().
* Reverts if the call fails for some reason (should never fail).
*/
function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
(bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return totalSupply;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identifier: 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-Identifier: 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-Identifier: 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-Identifier: 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-Identifier: 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-Identifier: 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 ERC165, 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
}
/**
* @dev Query if a contract implements a certain interface
* @param _interfaceId The interface identifier being queried, as specified in ERC-165
* @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise
*/
function supportsInterface(bytes4 _interfaceId) public pure returns (bool) {
return super.supportsInterface(_interfaceId) || _interfaceId == ARAGON_APP_INTERFACE_ID;
}
}
// 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/os/contracts/apps/disputable/DisputableAragonApp.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract DisputableAragonApp is IDisputable, AragonApp {
/* Validation errors */
string internal constant ERROR_SENDER_NOT_AGREEMENT = "DISPUTABLE_SENDER_NOT_AGREEMENT";
string internal constant ERROR_AGREEMENT_STATE_INVALID = "DISPUTABLE_AGREEMENT_STATE_INVAL";
// This role is used to protect who can challenge actions in derived Disputable apps. However, it is not required
// to be validated in the app itself as the connected Agreement is responsible for performing the check on a challenge.
// bytes32 public constant CHALLENGE_ROLE = keccak256("CHALLENGE_ROLE");
bytes32 public constant CHALLENGE_ROLE = 0xef025787d7cd1a96d9014b8dc7b44899b8c1350859fb9e1e05f5a546dd65158d;
// bytes32 public constant SET_AGREEMENT_ROLE = keccak256("SET_AGREEMENT_ROLE");
bytes32 public constant SET_AGREEMENT_ROLE = 0x8dad640ab1b088990c972676ada708447affc660890ec9fc9a5483241c49f036;
// bytes32 internal constant AGREEMENT_POSITION = keccak256("aragonOS.appStorage.agreement");
bytes32 internal constant AGREEMENT_POSITION = 0x6dbe80ccdeafbf5f3fff5738b224414f85e9370da36f61bf21c65159df7409e9;
modifier onlyAgreement() {
require(address(_getAgreement()) == msg.sender, ERROR_SENDER_NOT_AGREEMENT);
_;
}
/**
* @notice Challenge disputable action #`_disputableActionId`
* @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier
* is included. Subclasses should implement the internal implementation of the hook.
* @param _disputableActionId Identifier of the action to be challenged
* @param _challengeId Identifier of the challenge in the context of the Agreement
* @param _challenger Address that submitted the challenge
*/
function onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) external onlyAgreement {
_onDisputableActionChallenged(_disputableActionId, _challengeId, _challenger);
}
/**
* @notice Allow disputable action #`_disputableActionId`
* @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier
* is included. Subclasses should implement the internal implementation of the hook.
* @param _disputableActionId Identifier of the action to be allowed
*/
function onDisputableActionAllowed(uint256 _disputableActionId) external onlyAgreement {
_onDisputableActionAllowed(_disputableActionId);
}
/**
* @notice Reject disputable action #`_disputableActionId`
* @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier
* is included. Subclasses should implement the internal implementation of the hook.
* @param _disputableActionId Identifier of the action to be rejected
*/
function onDisputableActionRejected(uint256 _disputableActionId) external onlyAgreement {
_onDisputableActionRejected(_disputableActionId);
}
/**
* @notice Void disputable action #`_disputableActionId`
* @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier
* is included. Subclasses should implement the internal implementation of the hook.
* @param _disputableActionId Identifier of the action to be voided
*/
function onDisputableActionVoided(uint256 _disputableActionId) external onlyAgreement {
_onDisputableActionVoided(_disputableActionId);
}
/**
* @notice Set Agreement to `_agreement`
* @param _agreement Agreement instance to be set
*/
function setAgreement(IAgreement _agreement) external auth(SET_AGREEMENT_ROLE) {
IAgreement agreement = _getAgreement();
require(agreement == IAgreement(0) && _agreement != IAgreement(0), ERROR_AGREEMENT_STATE_INVALID);
AGREEMENT_POSITION.setStorageAddress(address(_agreement));
emit AgreementSet(_agreement);
}
/**
* @dev Tell the linked Agreement
* @return Agreement
*/
function getAgreement() external view returns (IAgreement) {
return _getAgreement();
}
/**
* @dev Query if a contract implements a certain interface
* @param _interfaceId The interface identifier being queried, as specified in ERC-165
* @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise
*/
function supportsInterface(bytes4 _interfaceId) public pure returns (bool) {
return super.supportsInterface(_interfaceId) || _interfaceId == DISPUTABLE_INTERFACE_ID;
}
/**
* @dev Internal implementation of the `onDisputableActionChallenged` hook
* @param _disputableActionId Identifier of the action to be challenged
* @param _challengeId Identifier of the challenge in the context of the Agreement
* @param _challenger Address that submitted the challenge
*/
function _onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) internal;
/**
* @dev Internal implementation of the `onDisputableActionRejected` hook
* @param _disputableActionId Identifier of the action to be rejected
*/
function _onDisputableActionRejected(uint256 _disputableActionId) internal;
/**
* @dev Internal implementation of the `onDisputableActionAllowed` hook
* @param _disputableActionId Identifier of the action to be allowed
*/
function _onDisputableActionAllowed(uint256 _disputableActionId) internal;
/**
* @dev Internal implementation of the `onDisputableActionVoided` hook
* @param _disputableActionId Identifier of the action to be voided
*/
function _onDisputableActionVoided(uint256 _disputableActionId) internal;
/**
* @dev Register a new disputable action in the Agreement
* @param _disputableActionId Identifier of the action in the context of the Disputable
* @param _context Link to human-readable context for the given action
* @param _submitter Address that submitted the action
* @return Unique identifier for the created action in the context of the Agreement
*/
function _registerDisputableAction(uint256 _disputableActionId, bytes _context, address _submitter) internal returns (uint256) {
IAgreement agreement = _ensureAgreement();
return agreement.newAction(_disputableActionId, _context, _submitter);
}
/**
* @dev Close disputable action in the Agreement
* @param _actionId Identifier of the action in the context of the Agreement
*/
function _closeDisputableAction(uint256 _actionId) internal {
IAgreement agreement = _ensureAgreement();
agreement.closeAction(_actionId);
}
/**
* @dev Tell the linked Agreement
* @return Agreement
*/
function _getAgreement() internal view returns (IAgreement) {
return IAgreement(AGREEMENT_POSITION.getStorageAddress());
}
/**
* @dev Tell the linked Agreement or revert if it has not been set
* @return Agreement
*/
function _ensureAgreement() internal view returns (IAgreement) {
IAgreement agreement = _getAgreement();
require(agreement != IAgreement(0), ERROR_AGREEMENT_STATE_INVALID);
return agreement;
}
}
// File: @aragon/os/contracts/forwarding/IAbstractForwarder.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
/**
* @title Abstract forwarder interface
* @dev This is the base interface for all forwarders.
* Forwarding allows separately installed applications (smart contracts implementing the forwarding interface) to execute multi-step actions via EVM scripts.
* You should only support the forwarding interface if your "action step" is asynchronous (e.g. requiring a delay period or a voting period).
* Note: you should **NOT** directly inherit from this interface; see one of the other, non-abstract interfaces available.
*/
contract IAbstractForwarder {
enum ForwarderType {
NOT_IMPLEMENTED,
NO_CONTEXT,
WITH_CONTEXT
}
/**
* @dev Tell whether the proposed forwarding path (an EVM script) from the given sender is allowed.
* However, this is not a strict guarantee of safety: the implemented `forward()` method is
* still allowed to revert even if `canForward()` returns true for the same parameters.
* @return True if the sender's proposed path is allowed
*/
function canForward(address sender, bytes evmScript) external view returns (bool);
/**
* @dev Tell the forwarder type
* @return Forwarder type
*/
function forwarderType() external pure returns (ForwarderType);
/**
* @dev Report whether the implementing app is a forwarder
* Required for backwards compatibility with aragonOS 4
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
}
// File: @aragon/os/contracts/forwarding/IForwarderWithContext.sol
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
/**
* @title Forwarder interface requiring context information
* @dev This forwarder interface allows for additional context to be attached to the action by the sender.
*/
contract IForwarderWithContext is IAbstractForwarder {
/**
* @dev Forward an EVM script with an attached context
*/
function forward(bytes evmScript, bytes context) external;
/**
* @dev Tell the forwarder type
* @return Always 2 (ForwarderType.WITH_CONTEXT)
*/
function forwarderType() external pure returns (ForwarderType) {
return ForwarderType.WITH_CONTEXT;
}
}
// 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/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/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 {
require(_value <= uint128(-1));
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 {
event NewFactoryCloneToken(address indexed _cloneToken, address indexed _parentToken, uint _snapshotBlock);
/// @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);
NewFactoryCloneToken(address(newToken), address(_parentToken), _snapshotBlock);
return newToken;
}
}
// File: contracts/DisputableVoting.sol
/*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract DisputableVoting is IForwarderWithContext, DisputableAragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
// bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant CREATE_VOTES_ROLE = 0xe7dcd7275292e064d090fbc5f3bd7995be23b502c1fed5cd94cfddbbdcd32bbc;
// bytes32 public constant CHANGE_VOTE_TIME_ROLE = keccak256("CHANGE_VOTE_TIME_ROLE");
bytes32 public constant CHANGE_VOTE_TIME_ROLE = 0xbc5d8ebc0830a2fed8649987b8263de1397b7fa892f3b87dc2d8cad35c691f86;
// bytes32 public constant CHANGE_SUPPORT_ROLE = keccak256("CHANGE_SUPPORT_ROLE");
bytes32 public constant CHANGE_SUPPORT_ROLE = 0xf3a5f71f3cb50dae9454dd13cdf0fd1b559f7e20d63c08902592486e6d460c90;
// bytes32 public constant CHANGE_QUORUM_ROLE = keccak256("CHANGE_QUORUM_ROLE");
bytes32 public constant CHANGE_QUORUM_ROLE = 0xa3f675280fb3c54662067f92659ca1ee3ef7c1a7f2a6ff03a5c4228aa26b6a82;
// bytes32 public constant CHANGE_DELEGATED_VOTING_PERIOD_ROLE = keccak256("CHANGE_DELEGATED_VOTING_PERIOD_ROLE");
bytes32 public constant CHANGE_DELEGATED_VOTING_PERIOD_ROLE = 0x59ba415d96e104e6483d76b79d9cd09941d04e229adcd62d7dc672c93975a19d;
// bytes32 public constant CHANGE_EXECUTION_DELAY_ROLE = keccak256("CHANGE_EXECUTION_DELAY_ROLE");
bytes32 public constant CHANGE_EXECUTION_DELAY_ROLE = 0x5e3a3edc315e366a0cc5c94ca94a8f9bbc2f1feebb2ef7704bfefcff0cdc4ee7;
// bytes32 public constant CHANGE_QUIET_ENDING_ROLE = keccak256("CHANGE_QUIET_ENDING_ROLE");
bytes32 public constant CHANGE_QUIET_ENDING_ROLE = 0x4f885d966bcd49734218a6e280d58c840b86e8cc13610b21ebd46f0b1da362c2;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint256 public constant MAX_VOTES_DELEGATION_SET_LENGTH = 70;
// Validation errors
string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE";
string private constant ERROR_VOTE_TIME_ZERO = "VOTING_VOTE_TIME_ZERO";
string private constant ERROR_TOKEN_NOT_CONTRACT = "VOTING_TOKEN_NOT_CONTRACT";
string private constant ERROR_SETTING_DOES_NOT_EXIST = "VOTING_SETTING_DOES_NOT_EXIST";
string private constant ERROR_CHANGE_QUORUM_TOO_BIG = "VOTING_CHANGE_QUORUM_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_SMALL = "VOTING_CHANGE_SUPPORT_TOO_SMALL";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPPORT_TOO_BIG";
string private constant ERROR_INVALID_DELEGATED_VOTING_PERIOD = "VOTING_INVALID_DLGT_VOTE_PERIOD";
string private constant ERROR_INVALID_QUIET_ENDING_PERIOD = "VOTING_INVALID_QUIET_END_PERIOD";
string private constant ERROR_INVALID_EXECUTION_SCRIPT = "VOTING_INVALID_EXECUTION_SCRIPT";
// Workflow errors
string private constant ERROR_CANNOT_FORWARD = "VOTING_CANNOT_FORWARD";
string private constant ERROR_NO_TOTAL_VOTING_POWER = "VOTING_NO_TOTAL_VOTING_POWER";
string private constant ERROR_CANNOT_VOTE = "VOTING_CANNOT_VOTE";
string private constant ERROR_NOT_REPRESENTATIVE = "VOTING_NOT_REPRESENTATIVE";
string private constant ERROR_PAST_REPRESENTATIVE_VOTING_WINDOW = "VOTING_PAST_REP_VOTING_WINDOW";
string private constant ERROR_DELEGATES_EXCEEDS_MAX_LEN = "VOTING_DELEGATES_EXCEEDS_MAX_LEN";
string private constant ERROR_CANNOT_PAUSE_VOTE = "VOTING_CANNOT_PAUSE_VOTE";
string private constant ERROR_VOTE_NOT_PAUSED = "VOTING_VOTE_NOT_PAUSED";
string private constant ERROR_CANNOT_EXECUTE = "VOTING_CANNOT_EXECUTE";
enum VoterState { Absent, Yea, Nay }
enum VoteStatus {
Normal, // A vote in a "normal" state of operation (not one of the below)--note that this state is not related to the vote being open
Paused, // A vote that is paused due to it having an open challenge or dispute
Cancelled, // A vote that has been explicitly cancelled due to a challenge or dispute
Executed // A vote that has been executed
}
struct Setting {
// "Base" duration of each vote -- vote lifespans may be adjusted by pause and extension durations
uint64 voteTime;
// Required voter support % (yes power / voted power) for a vote to pass
// Expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%
uint64 supportRequiredPct;
// Required voter quorum % (yes power / total power) for a vote to pass
// Expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%
// Must be <= supportRequiredPct to avoid votes being impossible to pass
uint64 minAcceptQuorumPct;
// Duration from the start of a vote that representatives are allowed to vote on behalf of principals
// Must be <= voteTime; duration is bound as [)
uint64 delegatedVotingPeriod;
// Duration before the end of a vote to detect non-quiet endings
// Must be <= voteTime; duration is bound as [)
uint64 quietEndingPeriod;
// Duration to extend a vote in case of non-quiet ending
uint64 quietEndingExtension;
// Duration to wait before a passed vote can be executed
// Duration is bound as [)
uint64 executionDelay;
}
struct VoteCast {
VoterState state;
address caster; // Caster of the vote (only stored if caster was not the representative)
}
struct Vote {
uint256 yea; // Voting power for
uint256 nay; // Voting power against
uint256 totalPower; // Total voting power (based on the snapshot block)
uint64 startDate; // Datetime when the vote was created
uint64 snapshotBlock; // Block number used to check voting power on attached token
VoteStatus status; // Status of the vote
uint256 settingId; // Identification number of the setting applicable to the vote
uint256 actionId; // Identification number of the associated disputable action on the attached Agreement
uint64 pausedAt; // Datetime when the vote was paused
uint64 pauseDuration; // Duration of the pause (only updated once resumed)
uint64 quietEndingExtensionDuration; // Duration a vote was extended due to non-quiet endings
VoterState quietEndingSnapshotSupport; // Snapshot of the vote's support at the beginning of the first quiet ending period
bytes32 executionScriptHash; // Hash of the EVM script attached to the vote
mapping (address => VoteCast) castVotes; // Mapping of voter address => more information about their cast vote
}
MiniMeToken public token; // Token for determining voting power; we assume it's not malicious
uint256 public settingsLength; // Number of settings created
mapping (uint256 => Setting) internal settings; // List of settings indexed by ID (starting at 0)
uint256 public votesLength; // Number of votes created
mapping (uint256 => Vote) internal votes; // List of votes indexed by ID (starting at 0)
mapping (address => address) internal representatives; // Mapping of voter => allowed representative
event NewSetting(uint256 settingId);
event ChangeVoteTime(uint64 voteTime);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
event ChangeDelegatedVotingPeriod(uint64 delegatedVotingPeriod);
event ChangeQuietEndingConfiguration(uint64 quietEndingPeriod, uint64 quietEndingExtension);
event ChangeExecutionDelay(uint64 executionDelay);
event StartVote(uint256 indexed voteId, address indexed creator, bytes context, bytes executionScript);
event PauseVote(uint256 indexed voteId, uint256 indexed challengeId);
event ResumeVote(uint256 indexed voteId);
event CancelVote(uint256 indexed voteId);
event ExecuteVote(uint256 indexed voteId);
event QuietEndingExtendVote(uint256 indexed voteId, bool passing);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, address caster);
event ChangeRepresentative(address indexed voter, address indexed representative);
event ProxyVoteFailure(uint256 indexed voteId, address indexed voter, address indexed representative);
/**
* @notice Initialize Disputable Voting with `_token.symbol(): string` for governance, a voting duration of `@transformTime(_voteTime)`, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, a delegated voting period of `@transformTime(_delegatedVotingPeriod), and a execution delay of `@transformTime(_executionDelay)`
* @param _token MiniMeToken Address that will be used as governance token
* @param _voteTime Base duration a vote will be open for voting
* @param _supportRequiredPct Required support % (yes power / voted power) for a vote to pass; expressed as a percentage of 10^18
* @param _minAcceptQuorumPct Required quorum % (yes power / total power) for a vote to pass; expressed as a percentage of 10^18
* @param _delegatedVotingPeriod Duration from the start of a vote that representatives are allowed to vote on behalf of principals
* @param _quietEndingPeriod Duration to detect non-quiet endings
* @param _quietEndingExtension Duration to extend a vote in case of non-quiet ending
* @param _executionDelay Duration to wait before a passed vote can be executed
*/
function initialize(
MiniMeToken _token,
uint64 _voteTime,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _delegatedVotingPeriod,
uint64 _quietEndingPeriod,
uint64 _quietEndingExtension,
uint64 _executionDelay
)
external
{
initialized();
require(isContract(_token), ERROR_TOKEN_NOT_CONTRACT);
token = _token;
(Setting storage setting, ) = _newSetting();
_changeVoteTime(setting, _voteTime);
_changeSupportRequiredPct(setting, _supportRequiredPct);
_changeMinAcceptQuorumPct(setting, _minAcceptQuorumPct);
_changeDelegatedVotingPeriod(setting, _delegatedVotingPeriod);
_changeQuietEndingConfiguration(setting, _quietEndingPeriod, _quietEndingExtension);
_changeExecutionDelay(setting, _executionDelay);
}
/**
* @notice Change vote time to `@transformTime(_voteTime)`
* @param _voteTime New vote time
*/
function changeVoteTime(uint64 _voteTime) external authP(CHANGE_VOTE_TIME_ROLE, arr(uint256(_voteTime))) {
Setting storage setting = _newCopiedSettings();
_changeVoteTime(setting, _voteTime);
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support; expressed as a percentage of 10^18
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(CHANGE_SUPPORT_ROLE, arr(uint256(_supportRequiredPct))) {
Setting storage setting = _newCopiedSettings();
_changeSupportRequiredPct(setting, _supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New minimum acceptance quorum; expressed as a percentage of 10^18
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(CHANGE_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct))) {
Setting storage setting = _newCopiedSettings();
_changeMinAcceptQuorumPct(setting, _minAcceptQuorumPct);
}
/**
* @notice Change delegated voting period to `@transformTime(_delegatedVotingPeriod)`
* @param _delegatedVotingPeriod New delegated voting period
*/
function changeDelegatedVotingPeriod(uint64 _delegatedVotingPeriod) external authP(CHANGE_DELEGATED_VOTING_PERIOD_ROLE, arr(uint256(_delegatedVotingPeriod))) {
Setting storage setting = _newCopiedSettings();
_changeDelegatedVotingPeriod(setting, _delegatedVotingPeriod);
}
/**
* @notice Change quiet ending period to `@transformTime(_quietEndingPeriod)` with extensions of `@transformTime(_quietEndingExtension)`
* @param _quietEndingPeriod New quiet ending period
* @param _quietEndingExtension New quiet ending extension
*/
function changeQuietEndingConfiguration(uint64 _quietEndingPeriod, uint64 _quietEndingExtension)
external
authP(CHANGE_QUIET_ENDING_ROLE, arr(uint256(_quietEndingPeriod), uint256(_quietEndingExtension)))
{
Setting storage setting = _newCopiedSettings();
_changeQuietEndingConfiguration(setting, _quietEndingPeriod, _quietEndingExtension);
}
/**
* @notice Change execution delay to `@transformTime(_executionDelay)`
* @param _executionDelay New execution delay
*/
function changeExecutionDelay(uint64 _executionDelay) external authP(CHANGE_EXECUTION_DELAY_ROLE, arr(uint256(_executionDelay))) {
Setting storage setting = _newCopiedSettings();
_changeExecutionDelay(setting, _executionDelay);
}
/**
* @notice Create a new vote about "`_context`"
* @param _executionScript Action (encoded as an EVM script) that will be allowed to execute if the vote passes
* @param _context Additional context for the vote, also used as the disputable action's context on the attached Agreement
* @return Identification number of the newly created vote
*/
function newVote(bytes _executionScript, bytes _context) external auth(CREATE_VOTES_ROLE) returns (uint256) {
return _newVote(_executionScript, _context);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote
* @param _supports Whether voter supports the vote
*/
function vote(uint256 _voteId, bool _supports) external {
Vote storage vote_ = _getVote(_voteId);
require(_canVote(vote_, msg.sender), ERROR_CANNOT_VOTE);
_castVote(vote_, _voteId, _supports, msg.sender, address(0));
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` on behalf of delegated voters
* @dev Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote
* @param _supports Whether the representative supports the vote
* @param _voters Addresses of the delegated voters to vote on behalf of
*/
function voteOnBehalfOf(uint256 _voteId, bool _supports, address[] _voters) external {
require(_voters.length <= MAX_VOTES_DELEGATION_SET_LENGTH, ERROR_DELEGATES_EXCEEDS_MAX_LEN);
Vote storage vote_ = _getVote(_voteId);
// Note that the period for representatives to vote can never go into a quiet ending
// extension, and so we don't need to check other timing-based pre-conditions
require(_canRepresentativesVote(vote_), ERROR_PAST_REPRESENTATIVE_VOTING_WINDOW);
for (uint256 i = 0; i < _voters.length; i++) {
address voter = _voters[i];
require(_hasVotingPower(vote_, voter), ERROR_CANNOT_VOTE);
require(_isRepresentativeOf(voter, msg.sender), ERROR_NOT_REPRESENTATIVE);
if (!_hasCastVote(vote_, voter)) {
_castVote(vote_, _voteId, _supports, voter, msg.sender);
} else {
emit ProxyVoteFailure(_voteId, voter, msg.sender);
}
}
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote
* @param _executionScript Action (encoded as an EVM script) to be executed, must match the one used when the vote was created
*/
function executeVote(uint256 _voteId, bytes _executionScript) external {
Vote storage vote_ = _getVote(_voteId);
require(_canExecute(vote_), ERROR_CANNOT_EXECUTE);
require(vote_.executionScriptHash == keccak256(_executionScript), ERROR_INVALID_EXECUTION_SCRIPT);
vote_.status = VoteStatus.Executed;
_closeDisputableAction(vote_.actionId);
// Add attached Agreement to blacklist to disallow the stored EVMScript from directly calling
// the Agreement from this app's context (e.g. maliciously closing a different action)
address[] memory blacklist = new address[](1);
blacklist[0] = address(_getAgreement());
runScript(_executionScript, new bytes(0), blacklist);
emit ExecuteVote(_voteId);
}
/**
* @notice `_representative == 0x0 ? 'Set your voting representative to ' + _representative : 'Remove your representative'`
* @param _representative Address of the representative who is allowed to vote on behalf of the sender. Use the zero address for none.
*/
function setRepresentative(address _representative) external isInitialized {
representatives[msg.sender] = _representative;
emit ChangeRepresentative(msg.sender, _representative);
}
// Forwarding external fns
/**
* @notice Create a vote to execute the desired action
* @dev IForwarderWithContext interface conformance.
* This app (as a DisputableAragonApp) is required to be the initial step in the forwarding chain.
* @param _evmScript Action (encoded as an EVM script) that will be allowed to execute if the vote passes
* @param _context Additional context for the vote, also used as the disputable action's context on the attached Agreement
*/
function forward(bytes _evmScript, bytes _context) external {
require(_canForward(msg.sender, _evmScript), ERROR_CANNOT_FORWARD);
_newVote(_evmScript, _context);
}
// Forwarding getter fns
/**
* @dev Tell if an address can forward actions (by creating a vote)
* IForwarderWithContext interface conformance
* @param _sender Address intending to forward an action
* @param _evmScript EVM script being forwarded
* @return True if the address is allowed create a vote containing the action
*/
function canForward(address _sender, bytes _evmScript) external view returns (bool) {
return _canForward(_sender, _evmScript);
}
// Disputable getter fns
/**
* @dev Tell if a vote can be challenged
* Called by the attached Agreement when a challenge is requested for the associated vote
* @param _voteId Identification number of the vote being queried
* @return True if the vote can be challenged
*/
function canChallenge(uint256 _voteId) external view returns (bool) {
Vote storage vote_ = _getVote(_voteId);
// Votes can only be challenged once
return vote_.pausedAt == 0 && _isVoteOpenForVoting(vote_, settings[vote_.settingId]);
}
/**
* @dev Tell if a vote can be closed
* Called by the attached Agreement when the action associated with the vote is requested to be manually closed
* @param _voteId Identification number of the vote being queried
* @return True if the vote can be closed
*/
function canClose(uint256 _voteId) external view returns (bool) {
Vote storage vote_ = _getVote(_voteId);
return (_isNormal(vote_) || _isExecuted(vote_)) && _hasEnded(vote_, settings[vote_.settingId]);
}
// Getter fns
/**
* @dev Tell the information for a setting
* Initialization check is implicitly provided by `_getSetting()` as new settings can only be
* created via `change*()` functions which require initialization
* @param _settingId Identification number of the setting
* @return voteTime Base vote duration
* @return supportRequiredPct Required support % (yes power / voted power) for a vote to pass; expressed as a percentage of 10^18
* @return minAcceptQuorumPct Required quorum % (yes power / total power) for a vote to pass; expressed as a percentage of 10^18
* @return delegatedVotingPeriod Duration of the delegated voting period
* @return quietEndingPeriod Duration to detect non-quiet endings
* @return quietEndingExtension Duration to extend a vote in case of non-quiet ending
* @return executionDelay Duration to wait before a passed vote can be executed
*/
function getSetting(uint256 _settingId)
external
view
returns (
uint64 voteTime,
uint64 supportRequiredPct,
uint64 minAcceptQuorumPct,
uint64 delegatedVotingPeriod,
uint64 quietEndingPeriod,
uint64 quietEndingExtension,
uint64 executionDelay
)
{
Setting storage setting = _getSetting(_settingId);
voteTime = setting.voteTime;
supportRequiredPct = setting.supportRequiredPct;
minAcceptQuorumPct = setting.minAcceptQuorumPct;
delegatedVotingPeriod = setting.delegatedVotingPeriod;
quietEndingPeriod = setting.quietEndingPeriod;
quietEndingExtension = setting.quietEndingExtension;
executionDelay = setting.executionDelay;
}
/**
* @dev Tell the information for a vote
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote
* @return yea Voting power for
* @return nay Voting power against
* @return totalPower Total voting power available (based on the snapshot block)
* @return startDate Datetime when the vote was created
* @return snapshotBlock Block number used to check voting power on attached token
* @return status Status of the vote
* @return settingId Identification number of the setting applicable to the vote
* @return actionId Identification number of the associated disputable action on the attached Agreement
* @return pausedAt Datetime when the vote was paused
* @return pauseDuration Duration of the pause (only updated once resumed)
* @return quietEndingExtensionDuration Duration a vote was extended due to non-quiet endings
* @return quietEndingSnapshotSupport Snapshot of the vote's support at the beginning of the first quiet ending period
* @return executionScriptHash Hash of the EVM script attached to the vote
*/
function getVote(uint256 _voteId)
external
view
returns (
uint256 yea,
uint256 nay,
uint256 totalPower,
uint64 startDate,
uint64 snapshotBlock,
VoteStatus status,
uint256 settingId,
uint256 actionId,
uint64 pausedAt,
uint64 pauseDuration,
uint64 quietEndingExtensionDuration,
VoterState quietEndingSnapshotSupport,
bytes32 executionScriptHash
)
{
Vote storage vote_ = _getVote(_voteId);
yea = vote_.yea;
nay = vote_.nay;
totalPower = vote_.totalPower;
startDate = vote_.startDate;
snapshotBlock = vote_.snapshotBlock;
status = vote_.status;
settingId = vote_.settingId;
actionId = vote_.actionId;
pausedAt = vote_.pausedAt;
pauseDuration = vote_.pauseDuration;
quietEndingExtensionDuration = vote_.quietEndingExtensionDuration;
quietEndingSnapshotSupport = vote_.quietEndingSnapshotSupport;
executionScriptHash = vote_.executionScriptHash;
}
/**
* @dev Tell the state of a voter for a vote
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote
* @param _voter Address of the voter being queried
* @return state Voter's cast state being queried
* @return caster Address of the vote's caster
*/
function getCastVote(uint256 _voteId, address _voter) external view returns (VoterState state, address caster) {
Vote storage vote_ = _getVote(_voteId);
state = _voterState(vote_, _voter);
caster = _voteCaster(vote_, _voter);
}
/**
* @dev Tell if a voter can participate in a vote
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote being queried
* @param _voter Address of the voter being queried
* @return True if the voter can participate in the vote
*/
function canVote(uint256 _voteId, address _voter) external view returns (bool) {
return _canVote(_getVote(_voteId), _voter);
}
/**
* @dev Tell if a representative can vote on behalf of delegated voters in a vote
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote being queried
* @param _voters Addresses of the delegated voters being queried
* @param _representative Address of the representative being queried
* @return True if the representative can vote on behalf of the delegated voters in the vote
*/
function canVoteOnBehalfOf(uint256 _voteId, address[] _voters, address _representative) external view returns (bool) {
require(_voters.length <= MAX_VOTES_DELEGATION_SET_LENGTH, ERROR_DELEGATES_EXCEEDS_MAX_LEN);
Vote storage vote_ = _getVote(_voteId);
if (!_canRepresentativesVote(vote_)) {
return false;
}
for (uint256 i = 0; i < _voters.length; i++) {
address voter = _voters[i];
if (!_hasVotingPower(vote_, voter) || !_isRepresentativeOf(voter, _representative) || _hasCastVote(vote_, voter)) {
return false;
}
}
return true;
}
/**
* @dev Tell if a vote can be executed
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote being queried
* @return True if the vote can be executed
*/
function canExecute(uint256 _voteId) external view returns (bool) {
return _canExecute(_getVote(_voteId));
}
/**
* @dev Tell if a vote is open for voting
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Identification number of the vote being queried
* @return True if the vote is open for voting
*/
function isVoteOpenForVoting(uint256 _voteId) external view returns (bool) {
Vote storage vote_ = _getVote(_voteId);
Setting storage setting = settings[vote_.settingId];
return _isVoteOpenForVoting(vote_, setting);
}
/**
* @dev Tell if a vote currently allows representatives to vote for delegated voters
* Initialization check is implicitly provided by `_getVote()` as new votes can only be
* created via `newVote()`, which requires initialization
* @param _voteId Vote identifier
* @return True if the vote currently allows representatives to vote
*/
function canRepresentativesVote(uint256 _voteId) external view returns (bool) {
Vote storage vote_ = _getVote(_voteId);
return _canRepresentativesVote(vote_);
}
/**
* @dev Tell if a representative currently represents another voter
* @param _voter Address of the delegated voter being queried
* @param _representative Address of the representative being queried
* @return True if the representative currently represents the voter
*/
function isRepresentativeOf(address _voter, address _representative) external view isInitialized returns (bool) {
return _isRepresentativeOf(_voter, _representative);
}
// DisputableAragonApp callback implementations
/**
* @dev Received when a vote is challenged
* @param _voteId Identification number of the vote
* @param _challengeId Identification number of the challenge associated to the vote on the attached Agreement
*/
function _onDisputableActionChallenged(uint256 _voteId, uint256 _challengeId, address /* _challenger */) internal {
Vote storage vote_ = _getVote(_voteId);
require(_isNormal(vote_), ERROR_CANNOT_PAUSE_VOTE);
vote_.status = VoteStatus.Paused;
vote_.pausedAt = getTimestamp64();
emit PauseVote(_voteId, _challengeId);
}
/**
* @dev Received when a vote was ruled in favour of the submitter
* @param _voteId Identification number of the vote
*/
function _onDisputableActionAllowed(uint256 _voteId) internal {
Vote storage vote_ = _getVote(_voteId);
require(_isPaused(vote_), ERROR_VOTE_NOT_PAUSED);
vote_.status = VoteStatus.Normal;
vote_.pauseDuration = getTimestamp64().sub(vote_.pausedAt);
emit ResumeVote(_voteId);
}
/**
* @dev Received when a vote was ruled in favour of the challenger
* @param _voteId Identification number of the vote
*/
function _onDisputableActionRejected(uint256 _voteId) internal {
Vote storage vote_ = _getVote(_voteId);
require(_isPaused(vote_), ERROR_VOTE_NOT_PAUSED);
vote_.status = VoteStatus.Cancelled;
vote_.pauseDuration = getTimestamp64().sub(vote_.pausedAt);
emit CancelVote(_voteId);
}
/**
* @dev Received when a vote was ruled as void
* @param _voteId Identification number of the vote
*/
function _onDisputableActionVoided(uint256 _voteId) internal {
// When a challenged vote is ruled as voided, it is considered as being allowed.
// This could be the case for challenges where the attached Agreement's arbitrator refuses to rule the case.
_onDisputableActionAllowed(_voteId);
}
// Internal fns
/**
* @dev Create a new empty setting instance
* @return New setting's instance
* @return New setting's identification number
*/
function _newSetting() internal returns (Setting storage setting, uint256 settingId) {
settingId = settingsLength++;
setting = settings[settingId];
emit NewSetting(settingId);
}
/**
* @dev Create a copy of the current settings as a new setting instance
* @return New setting's instance
*/
function _newCopiedSettings() internal returns (Setting storage) {
(Setting storage to, uint256 settingId) = _newSetting();
Setting storage from = _getSetting(settingId - 1);
to.voteTime = from.voteTime;
to.supportRequiredPct = from.supportRequiredPct;
to.minAcceptQuorumPct = from.minAcceptQuorumPct;
to.delegatedVotingPeriod = from.delegatedVotingPeriod;
to.quietEndingPeriod = from.quietEndingPeriod;
to.quietEndingExtension = from.quietEndingExtension;
to.executionDelay = from.executionDelay;
return to;
}
/**
* @dev Change vote time
* @param _setting Setting instance to update
* @param _voteTime New vote time
*/
function _changeVoteTime(Setting storage _setting, uint64 _voteTime) internal {
require(_voteTime > 0, ERROR_VOTE_TIME_ZERO);
_setting.voteTime = _voteTime;
emit ChangeVoteTime(_voteTime);
}
/**
* @dev Change the required support
* @param _setting Setting instance to update
* @param _supportRequiredPct New required support; expressed as a percentage of 10^18
*/
function _changeSupportRequiredPct(Setting storage _setting, uint64 _supportRequiredPct) internal {
require(_setting.minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_TOO_SMALL);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
_setting.supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @dev Change the minimum acceptance quorum
* @param _setting Setting instance to update
* @param _minAcceptQuorumPct New acceptance quorum; expressed as a percentage of 10^18
*/
function _changeMinAcceptQuorumPct(Setting storage _setting, uint64 _minAcceptQuorumPct) internal {
require(_minAcceptQuorumPct <= _setting.supportRequiredPct, ERROR_CHANGE_QUORUM_TOO_BIG);
_setting.minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @dev Change the delegated voting period
* @param _setting Setting instance to update
* @param _delegatedVotingPeriod New delegated voting period
*/
function _changeDelegatedVotingPeriod(Setting storage _setting, uint64 _delegatedVotingPeriod) internal {
require(_delegatedVotingPeriod <= _setting.voteTime, ERROR_INVALID_DELEGATED_VOTING_PERIOD);
_setting.delegatedVotingPeriod = _delegatedVotingPeriod;
emit ChangeDelegatedVotingPeriod(_delegatedVotingPeriod);
}
/**
* @dev Change the quiet ending configuration
* @param _setting Setting instance to update
* @param _quietEndingPeriod New quiet ending period
* @param _quietEndingExtension New quiet ending extension
*/
function _changeQuietEndingConfiguration(Setting storage _setting, uint64 _quietEndingPeriod, uint64 _quietEndingExtension) internal {
require(_quietEndingPeriod <= _setting.voteTime, ERROR_INVALID_QUIET_ENDING_PERIOD);
_setting.quietEndingPeriod = _quietEndingPeriod;
_setting.quietEndingExtension = _quietEndingExtension;
emit ChangeQuietEndingConfiguration(_quietEndingPeriod, _quietEndingExtension);
}
/**
* @dev Change the execution delay
* @param _setting Setting instance to update
* @param _executionDelay New execution delay
*/
function _changeExecutionDelay(Setting storage _setting, uint64 _executionDelay) internal {
_setting.executionDelay = _executionDelay;
emit ChangeExecutionDelay(_executionDelay);
}
/**
* @dev Create a new vote
* @param _executionScript Action (encoded as an EVM script) that will be allowed to execute if the vote passes
* @param _context Additional context for the vote, also used as the disputable action's context on the attached Agreement
* @return voteId Identification number for the newly created vote
*/
function _newVote(bytes _executionScript, bytes _context) internal returns (uint256 voteId) {
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 totalPower = token.totalSupplyAt(snapshotBlock);
require(totalPower > 0, ERROR_NO_TOTAL_VOTING_POWER);
voteId = votesLength++;
Vote storage vote_ = votes[voteId];
vote_.totalPower = totalPower;
vote_.startDate = getTimestamp64();
vote_.snapshotBlock = snapshotBlock;
vote_.status = VoteStatus.Normal;
vote_.settingId = _getCurrentSettingId();
vote_.executionScriptHash = keccak256(_executionScript);
// Notify the attached Agreement about the new vote; this is mandatory in making the vote disputable
// Note that we send `msg.sender` as the action's submitter--the attached Agreement may expect to be able to pull funds from this account
vote_.actionId = _registerDisputableAction(voteId, _context, msg.sender);
emit StartVote(voteId, msg.sender, _context, _executionScript);
}
/**
* @dev Cast a vote
* Assumes all eligibility checks have passed for the given vote and voter
* @param _vote Vote instance
* @param _voteId Identification number of vote
* @param _supports Whether principal voter supports the vote
* @param _voter Address of principal voter
* @param _caster Address of vote caster, if voting via representative
*/
function _castVote(Vote storage _vote, uint256 _voteId, bool _supports, address _voter, address _caster) internal {
Setting storage setting = settings[_vote.settingId];
if (_hasStartedQuietEndingPeriod(_vote, setting)) {
_ensureQuietEnding(_vote, setting, _voteId);
}
uint256 yeas = _vote.yea;
uint256 nays = _vote.nay;
uint256 voterStake = token.balanceOfAt(_voter, _vote.snapshotBlock);
VoteCast storage castVote = _vote.castVotes[_voter];
VoterState previousVoterState = castVote.state;
// If voter had previously voted, reset their vote
// Note that votes can only be changed once by the principal voter to overrule their representative's vote
if (previousVoterState == VoterState.Yea) {
yeas = yeas.sub(voterStake);
} else if (previousVoterState == VoterState.Nay) {
nays = nays.sub(voterStake);
}
if (_supports) {
yeas = yeas.add(voterStake);
} else {
nays = nays.add(voterStake);
}
_vote.yea = yeas;
_vote.nay = nays;
castVote.state = _voterStateFor(_supports);
castVote.caster = _caster;
emit CastVote(_voteId, _voter, _supports, _caster == address(0) ? _voter : _caster);
}
/**
* @dev Ensure we keep track of the information related for detecting a quiet ending
* @param _vote Vote instance
* @param _setting Setting instance applicable to the vote
* @param _voteId Identification number of the vote
*/
function _ensureQuietEnding(Vote storage _vote, Setting storage _setting, uint256 _voteId) internal {
bool isAccepted = _isAccepted(_vote, _setting);
if (_vote.quietEndingSnapshotSupport == VoterState.Absent) {
// If we do not have a snapshot of the support yet, simply store the given value.
// Note that if there are no votes during the quiet ending period, it is obviously impossible for the vote to be flipped and
// this snapshot is never stored.
_vote.quietEndingSnapshotSupport = _voterStateFor(isAccepted);
} else {
// We are calculating quiet ending extensions via "rolling snapshots", and so we only update the vote's cached duration once
// the last period is over and we've confirmed the flip.
if (getTimestamp() >= _lastComputedVoteEndDate(_vote, _setting)) {
_vote.quietEndingExtensionDuration = _vote.quietEndingExtensionDuration.add(_setting.quietEndingExtension);
emit QuietEndingExtendVote(_voteId, isAccepted);
}
}
}
/**
* @dev Fetch a setting's instance by identification number
* @return Identification number of the current setting
*/
function _getSetting(uint256 _settingId) internal view returns (Setting storage) {
require(_settingId < settingsLength, ERROR_SETTING_DOES_NOT_EXIST);
return settings[_settingId];
}
/**
* @dev Tell the identification number of the current setting
* @return Identification number of the current setting
*/
function _getCurrentSettingId() internal view returns (uint256) {
// No need for SafeMath, note that a new setting is created during initialization
return settingsLength - 1;
}
/**
* @dev Fetch a vote instance by identification number
* @param _voteId Identification number of the vote
* @return Vote instance
*/
function _getVote(uint256 _voteId) internal view returns (Vote storage) {
require(_voteId < votesLength, ERROR_NO_VOTE);
return votes[_voteId];
}
/**
* @dev Tell if a voter can participate in a vote.
* Note that a voter cannot change their vote once cast, except by the principal voter to overrule their representative's vote.
* @param _vote Vote instance being queried
* @param _voter Address of the voter being queried
* @return True if the voter can participate a certain vote
*/
function _canVote(Vote storage _vote, address _voter) internal view returns (bool) {
Setting storage setting = settings[_vote.settingId];
return _isVoteOpenForVoting(_vote, setting) && _hasVotingPower(_vote, _voter) && _voteCaster(_vote, _voter) != _voter;
}
/**
* @dev Tell if a vote currently allows representatives to vote for delegated voters
* @param _vote Vote instance being queried
* @return True if the vote currently allows representatives to vote
*/
function _canRepresentativesVote(Vote storage _vote) internal view returns (bool) {
return _isNormal(_vote) && !_hasFinishedDelegatedVotingPeriod(_vote, settings[_vote.settingId]);
}
/**
* @dev Tell if a vote can be executed
* @param _vote Vote instance being queried
* @return True if the vote can be executed
*/
function _canExecute(Vote storage _vote) internal view returns (bool) {
// If the vote is executed, paused, or cancelled, it cannot be executed
if (!_isNormal(_vote)) {
return false;
}
Setting storage setting = settings[_vote.settingId];
// If the vote is still open, it cannot be executed
if (!_hasEnded(_vote, setting)) {
return false;
}
// If the vote's execution delay has not finished yet, it cannot be executed
if (!_hasFinishedExecutionDelay(_vote, setting)) {
return false;
}
// Check the vote has enough support and has reached the min quorum
return _isAccepted(_vote, setting);
}
/**
* @dev Tell if a vote is in a "normal" non-exceptional state
* @param _vote Vote instance being queried
* @return True if the vote is normal
*/
function _isNormal(Vote storage _vote) internal view returns (bool) {
return _vote.status == VoteStatus.Normal;
}
/**
* @dev Tell if a vote is paused
* @param _vote Vote instance being queried
* @return True if the vote is paused
*/
function _isPaused(Vote storage _vote) internal view returns (bool) {
return _vote.status == VoteStatus.Paused;
}
/**
* @dev Tell if a vote was executed
* @param _vote Vote instance being queried
* @return True if the vote was executed
*/
function _isExecuted(Vote storage _vote) internal view returns (bool) {
return _vote.status == VoteStatus.Executed;
}
/**
* @dev Tell if a vote is currently accepted
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return True if the vote is accepted
*/
function _isAccepted(Vote storage _vote, Setting storage _setting) internal view returns (bool) {
uint256 yeas = _vote.yea;
uint256 nays = _vote.nay;
uint64 supportRequiredPct = _setting.supportRequiredPct;
uint64 minimumAcceptanceQuorumPct = _setting.minAcceptQuorumPct;
return _isValuePct(yeas, yeas.add(nays), supportRequiredPct) &&
_isValuePct(yeas, _vote.totalPower, minimumAcceptanceQuorumPct);
}
/**
* @dev Tell if a vote is open for voting
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return True if the vote is open for voting
*/
function _isVoteOpenForVoting(Vote storage _vote, Setting storage _setting) internal view returns (bool) {
return _isNormal(_vote) && !_hasEnded(_vote, _setting);
}
/**
* @dev Tell if a vote has ended
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return True if the vote has ended
*/
function _hasEnded(Vote storage _vote, Setting storage _setting) internal view returns (bool) {
return getTimestamp() >= _currentVoteEndDate(_vote, _setting);
}
/**
* @dev Tell if a vote's delegated voting period has finished
* This function doesn't ensure that the vote is still open
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return True if the vote's delegated voting period has finished
*/
function _hasFinishedDelegatedVotingPeriod(Vote storage _vote, Setting storage _setting) internal view returns (bool) {
uint64 baseDelegatedVotingPeriodEndDate = _vote.startDate.add(_setting.delegatedVotingPeriod);
// If the vote was paused before the delegated voting period ended, we need to extend it
uint64 pausedAt = _vote.pausedAt;
uint64 pauseDuration = _vote.pauseDuration;
uint64 actualDeletedVotingEndDate = pausedAt != 0 && pausedAt < baseDelegatedVotingPeriodEndDate
? baseDelegatedVotingPeriodEndDate.add(pauseDuration)
: baseDelegatedVotingPeriodEndDate;
return getTimestamp() >= actualDeletedVotingEndDate;
}
/**
* @dev Tell if a vote's quiet ending period has started
* This function doesn't ensure that the vote is still open
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return True if the vote's quiet ending period has started
*/
function _hasStartedQuietEndingPeriod(Vote storage _vote, Setting storage _setting) internal view returns (bool) {
uint64 voteBaseEndDate = _baseVoteEndDate(_vote, _setting);
uint64 baseQuietEndingPeriodStartDate = voteBaseEndDate.sub(_setting.quietEndingPeriod);
// If the vote was paused before the quiet ending period started, we need to delay it
uint64 pausedAt = _vote.pausedAt;
uint64 pauseDuration = _vote.pauseDuration;
uint64 actualQuietEndingPeriodStartDate = pausedAt != 0 && pausedAt < baseQuietEndingPeriodStartDate
? baseQuietEndingPeriodStartDate.add(pauseDuration)
: baseQuietEndingPeriodStartDate;
return getTimestamp() >= actualQuietEndingPeriodStartDate;
}
/**
* @dev Tell if a vote's execution delay has finished
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return True if the vote's execution delay has finished
*/
function _hasFinishedExecutionDelay(Vote storage _vote, Setting storage _setting) internal view returns (bool) {
uint64 endDate = _currentVoteEndDate(_vote, _setting);
return getTimestamp() >= endDate.add(_setting.executionDelay);
}
/**
* @dev Calculate the original end date of a vote
* It does not consider extensions from pauses or the quiet ending mechanism
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return Datetime of the vote's original end date
*/
function _baseVoteEndDate(Vote storage _vote, Setting storage _setting) internal view returns (uint64) {
return _vote.startDate.add(_setting.voteTime);
}
/**
* @dev Tell the last computed end date of a vote.
* It considers extensions from pauses and the quiet ending mechanism.
* We call this the "last computed end date" because we use the currently cached quiet ending extension, which may be off-by-one from reality
* because it is only updated on the first vote in a new extension (which may never happen).
* The pause duration will only be included after the vote has "resumed" from its pause, as we do not know how long the pause will be in advance.
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return Datetime of the vote's last computed end date
*/
function _lastComputedVoteEndDate(Vote storage _vote, Setting storage _setting) internal view returns (uint64) {
uint64 endDateAfterPause = _baseVoteEndDate(_vote, _setting).add(_vote.pauseDuration);
return endDateAfterPause.add(_vote.quietEndingExtensionDuration);
}
/**
* @dev Calculate the current end date of a vote.
* It considers extensions from pauses and the quiet ending mechanism.
* We call this the "current end date" because it takes into account a posssibly "missing" quiet ending extension that was not cached with the vote.
* The pause duration will only be included after the vote has "resumed" from its pause, as we do not know how long the pause will be in advance.
* @param _vote Vote instance being queried
* @param _setting Setting instance applicable to the vote
* @return Datetime of the vote's current end date
*/
function _currentVoteEndDate(Vote storage _vote, Setting storage _setting) internal view returns (uint64) {
uint64 lastComputedEndDate = _lastComputedVoteEndDate(_vote, _setting);
// The last computed end date is correct if we have not passed it yet or if no flip was detected in the last extension
if (getTimestamp() < lastComputedEndDate || !_wasFlipped(_vote)) {
return lastComputedEndDate;
}
// Otherwise, since the last computed end date was reached and included a flip, we need to extend the end date by one more period
return lastComputedEndDate.add(_setting.quietEndingExtension);
}
/**
* @dev Tell if a vote was flipped in its most recent quiet ending period
* This function assumes that it will only be called after the most recent quiet ending period has already ended
* @param _vote Vote instance being queried
* @return True if the vote was flipped
*/
function _wasFlipped(Vote storage _vote) internal view returns (bool) {
// If there was no snapshot taken, it means no one voted during the quiet ending period. Thus, it cannot have been flipped.
VoterState snapshotSupport = _vote.quietEndingSnapshotSupport;
if (snapshotSupport == VoterState.Absent) {
return false;
}
// Otherwise, we calculate if the vote was flipped by comparing its current acceptance state to its last state at the start of the extension period
bool wasInitiallyAccepted = snapshotSupport == VoterState.Yea;
Setting storage setting = settings[_vote.settingId];
uint256 currentExtensions = _vote.quietEndingExtensionDuration / setting.quietEndingExtension;
bool wasAcceptedBeforeLastFlip = wasInitiallyAccepted != (currentExtensions % 2 != 0);
return wasAcceptedBeforeLastFlip != _isAccepted(_vote, setting);
}
/**
* @dev Tell if a voter has voting power for a vote
* @param _vote Vote instance being queried
* @param _voter Address of the voter being queried
* @return True if the voter has voting power for a certain vote
*/
function _hasVotingPower(Vote storage _vote, address _voter) internal view returns (bool) {
return token.balanceOfAt(_voter, _vote.snapshotBlock) > 0;
}
/**
* @dev Tell if a voter has cast their choice in a vote (by themselves or via a representative)
* @param _vote Vote instance being queried
* @param _voter Address of the voter being queried
* @return True if the voter has cast their choice in the vote
*/
function _hasCastVote(Vote storage _vote, address _voter) internal view returns (bool) {
return _voterState(_vote, _voter) != VoterState.Absent;
}
/**
* @dev Tell the state of a voter for a vote
* @param _vote Vote instance being queried
* @param _voter Address of the voter being queried
* @return Voting state of the voter
*/
function _voterState(Vote storage _vote, address _voter) internal view returns (VoterState) {
return _vote.castVotes[_voter].state;
}
/**
* @dev Tell the caster of a voter on a vote
* @param _vote Vote instance being queried
* @param _voter Address of the voter being queried
* @return Address of the vote's caster
*/
function _voteCaster(Vote storage _vote, address _voter) internal view returns (address) {
if (!_hasCastVote(_vote, _voter)) {
return address(0);
}
address _caster = _vote.castVotes[_voter].caster;
return _caster == address(0) ? _voter : _caster;
}
/**
* @dev Tell if a representative currently represents another voter
* @param _voter Address of the delegated voter being queried
* @param _representative Address of the representative being queried
* @return True if the representative currently represents the voter
*/
function _isRepresentativeOf(address _voter, address _representative) internal view returns (bool) {
return representatives[_voter] == _representative;
}
/**
* @dev Tell if an address can forward actions
* @param _sender Address intending to forward an action
* @return True if the address can create votes
*/
function _canForward(address _sender, bytes) internal view returns (bool) {
IAgreement agreement = _getAgreement();
// To make sure the sender address is reachable by ACL oracles, we need to pass it as the first argument.
// Permissions set with ANY_ENTITY do not provide the original sender's address into the ACL Oracle's `grantee` argument.
return agreement != IAgreement(0) && canPerform(_sender, CREATE_VOTES_ROLE, arr(_sender));
}
/**
* @dev Calculates whether a given value is greater than a percentage of its total
* @param _value Numerator
* @param _total Divisor
* @param _pct Required percentage necessary, expressed as a percentage of 10^18
* @return True if the value is above the required percentage
*/
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;
}
/**
* @dev Translate a voter's support into a voter state
* @param _supports Whether voter supports the vote
* @return Voter state, as an enum
*/
function _voterStateFor(bool _supports) internal pure returns (VoterState) {
return _supports ? VoterState.Yea : VoterState.Nay;
}
} | Tell the information for a setting Initialization check is implicitly provided by `_getSetting()` as new settings can only be created via `change()` functions which require initialization _settingId Identification number of the setting return voteTime Base vote duration return supportRequiredPct Required support % (yes power / voted power) for a vote to pass; expressed as a percentage of 10^18 return minAcceptQuorumPct Required quorum % (yes power / total power) for a vote to pass; expressed as a percentage of 10^18 return delegatedVotingPeriod Duration of the delegated voting period return quietEndingPeriod Duration to detect non-quiet endings return quietEndingExtension Duration to extend a vote in case of non-quiet ending return executionDelay Duration to wait before a passed vote can be executed/ | function getSetting(uint256 _settingId)
external
view
returns (
uint64 voteTime,
uint64 supportRequiredPct,
uint64 minAcceptQuorumPct,
uint64 delegatedVotingPeriod,
uint64 quietEndingPeriod,
uint64 quietEndingExtension,
uint64 executionDelay
)
{
Setting storage setting = _getSetting(_settingId);
voteTime = setting.voteTime;
supportRequiredPct = setting.supportRequiredPct;
minAcceptQuorumPct = setting.minAcceptQuorumPct;
delegatedVotingPeriod = setting.delegatedVotingPeriod;
quietEndingPeriod = setting.quietEndingPeriod;
quietEndingExtension = setting.quietEndingExtension;
executionDelay = setting.executionDelay;
}
| 15,422,817 |
pragma solidity ^0.4.25;
contract Richer3D {
using SafeMath for *;
//************
//Game Setting
//************
string constant public name = "Richer3D";
string constant public symbol = "R3D";
address constant private sysAdminAddress = 0x4A3913ce9e8882b418a0Be5A43d2C319c3F0a7Bd;
address constant private sysInviterAddress = 0xC5E41EC7fa56C0656Bc6d7371a8706Eb9dfcBF61;
address constant private sysDevelopAddress = 0xCf3A25b73A493F96C15c8198319F0218aE8cAA4A;
address constant private p3dInviterAddress = 0x82Fc4514968b0c5FdDfA97ed005A01843d0E117d;
uint256 constant cycleTime = 24 hours;
bool calculating_target = false;
//************
//Game Data
//************
uint256 private roundNumber;
uint256 private dayNumber;
uint256 private totalPlayerNumber;
uint256 private platformBalance;
//*************
//Game DataBase
//*************
mapping(uint256=>DataModal.RoundInfo) private rInfoXrID;
mapping(address=>DataModal.PlayerInfo) private pInfoXpAdd;
mapping(address=>uint256) private pIDXpAdd;
mapping(uint256=>address) private pAddXpID;
//*************
// P3D Data
//*************
HourglassInterface constant p3dContract = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
mapping(uint256=>uint256) private p3dDividesXroundID;
//*************
//Game Events
//*************
event newPlayerJoinGameEvent(address indexed _address,uint256 indexed _amount,bool indexed _JoinWithEth,uint256 _timestamp);
event calculateTargetEvent(uint256 indexed _roundID);
constructor() public {
dayNumber = 1;
}
function() external payable {
}
//************
//Game payable
//************
function joinGameWithInviterID(uint256 _inviterID) public payable {
uint256 _timestamp = now;
address _senderAddress = msg.sender;
uint256 _eth = msg.value;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) < cycleTime,"Waiting for settlement");
if(pIDXpAdd[_senderAddress] < 1) {
registerWithInviterID(_inviterID);
}
buyCore(_senderAddress,pInfoXpAdd[_senderAddress].inviterAddress,_eth);
emit newPlayerJoinGameEvent(msg.sender,msg.value,true,_timestamp);
}
function joinGameWithInviterIDForAddress(uint256 _inviterID,address _address) public payable {
uint256 _timestamp = now;
address _senderAddress = _address;
uint256 _eth = msg.value;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) < cycleTime,"Waiting for settlement");
if(pIDXpAdd[_senderAddress] < 1) {
registerWithInviterID(_inviterID);
}
buyCore(_senderAddress,pInfoXpAdd[_senderAddress].inviterAddress,_eth);
emit newPlayerJoinGameEvent(msg.sender,msg.value,true,_timestamp);
}
//********************
// Method need Gas
//********************
function joinGameWithBalance(uint256 _amount) public {
uint256 _timestamp = now;
address _senderAddress = msg.sender;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) < cycleTime,"Waiting for settlement");
uint256 balance = getUserBalance(_senderAddress);
require(balance >= _amount,"balance is not enough");
buyCore(_senderAddress,pInfoXpAdd[_senderAddress].inviterAddress,_amount);
pInfoXpAdd[_senderAddress].withDrawNumber = pInfoXpAdd[_senderAddress].withDrawNumber.sub(_amount);
emit newPlayerJoinGameEvent(_senderAddress,_amount,false,_timestamp);
}
function calculateTarget() public {
require(calculating_target == false,"Waiting....");
calculating_target = true;
uint256 _timestamp = now;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) >= cycleTime,"Less than cycle Time from last operation");
//allocate p3d dividends to contract
uint256 dividends = p3dContract.myDividends(true);
if(dividends > 0) {
if(rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber > 0) {
p3dDividesXroundID[roundNumber] = p3dDividesXroundID[roundNumber].add(dividends);
p3dContract.withdraw();
} else {
platformBalance = platformBalance.add(dividends).add(p3dDividesXroundID[roundNumber]);
p3dContract.withdraw();
}
}
uint256 increaseBalance = getIncreaseBalance(dayNumber,roundNumber);
uint256 targetBalance = getDailyTarget(roundNumber,dayNumber);
uint256 ethForP3D = increaseBalance.div(100);
if(increaseBalance >= targetBalance) {
//buy p3d
if(increaseBalance > 0) {
p3dContract.buy.value(ethForP3D)(p3dInviterAddress);
}
//continue
dayNumber++;
rInfoXrID[roundNumber].totalDay = dayNumber;
if(rInfoXrID[roundNumber].startTime == 0) {
rInfoXrID[roundNumber].startTime = _timestamp;
rInfoXrID[roundNumber].lastCalculateTime = _timestamp;
} else {
rInfoXrID[roundNumber].lastCalculateTime = _timestamp;
}
//dividends for mine holder
rInfoXrID[roundNumber].increaseETH = rInfoXrID[roundNumber].increaseETH.sub(getETHNeedPay(roundNumber,dayNumber.sub(1))).sub(ethForP3D);
emit calculateTargetEvent(0);
} else {
//Game over, start new round
bool haveWinner = false;
if(dayNumber > 1) {
sendBalanceForDevelop(roundNumber);
if(platformBalance > 0) {
uint256 platformBalanceAmount = platformBalance;
platformBalance = 0;
sysAdminAddress.transfer(platformBalanceAmount);
}
haveWinner = true;
}
rInfoXrID[roundNumber].winnerDay = dayNumber.sub(1);
roundNumber++;
dayNumber = 1;
if(haveWinner) {
rInfoXrID[roundNumber].bounsInitNumber = getBounsWithRoundID(roundNumber.sub(1)).div(10);
} else {
rInfoXrID[roundNumber].bounsInitNumber = getBounsWithRoundID(roundNumber.sub(1));
}
rInfoXrID[roundNumber].totalDay = 1;
rInfoXrID[roundNumber].startTime = _timestamp;
rInfoXrID[roundNumber].lastCalculateTime = _timestamp;
emit calculateTargetEvent(roundNumber);
}
calculating_target = false;
}
function registerWithInviterID(uint256 _inviterID) private {
address _senderAddress = msg.sender;
totalPlayerNumber++;
pIDXpAdd[_senderAddress] = totalPlayerNumber;
pAddXpID[totalPlayerNumber] = _senderAddress;
pInfoXpAdd[_senderAddress].inviterAddress = pAddXpID[_inviterID];
}
function buyCore(address _playerAddress,address _inviterAddress,uint256 _amount) private {
require(_amount >= 0.01 ether,"You need to pay 0.01 ether at lesat");
//10 percent of the investment amount belongs to the inviter
address _senderAddress = _playerAddress;
if(_inviterAddress == address(0) || _inviterAddress == _senderAddress) {
platformBalance = platformBalance.add(_amount/10);
} else {
pInfoXpAdd[_inviterAddress].inviteEarnings = pInfoXpAdd[_inviterAddress].inviteEarnings.add(_amount/10);
}
//Record the order of purchase for each user
uint256 playerIndex = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber.add(1);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber = playerIndex;
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].addXIndex[playerIndex] = _senderAddress;
//After the user purchases, they can add 50% more, except for the first user
if(rInfoXrID[roundNumber].increaseETH > 0) {
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseMine = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseMine.add(_amount*5/2);
rInfoXrID[roundNumber].totalMine = rInfoXrID[roundNumber].totalMine.add(_amount*15/2);
} else {
rInfoXrID[roundNumber].totalMine = rInfoXrID[roundNumber].totalMine.add(_amount*5);
}
//Record the accumulated ETH in the prize pool, the newly added ETH each day, the ore and the ore actually purchased by each user
rInfoXrID[roundNumber].increaseETH = rInfoXrID[roundNumber].increaseETH.add(_amount).sub(_amount/10);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseETH = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseETH.add(_amount).sub(_amount/10);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].actualMine = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].actualMine.add(_amount*5);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].mineAmountXAddress[_senderAddress] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].mineAmountXAddress[_senderAddress].add(_amount*5);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].ethPayAmountXAddress[_senderAddress] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].ethPayAmountXAddress[_senderAddress].add(_amount);
}
function playerWithdraw(uint256 _amount) public {
address _senderAddress = msg.sender;
uint256 balance = getUserBalance(_senderAddress);
require(balance>=_amount,"Lack of balance");
//The platform charges users 1% of the commission fee, and the rest is withdrawn to the user account
platformBalance = platformBalance.add(_amount.div(100));
pInfoXpAdd[_senderAddress].withDrawNumber = pInfoXpAdd[_senderAddress].withDrawNumber.add(_amount);
_senderAddress.transfer(_amount.sub(_amount.div(100)));
}
function sendBalanceForDevelop(uint256 _roundID) private {
uint256 bouns = getBounsWithRoundID(_roundID).div(5);
sysDevelopAddress.transfer(bouns.div(2));
sysInviterAddress.transfer(bouns.sub(bouns.div(2)));
}
//If no users participate in the game for 10 consecutive rounds, the administrator can destroy the contract
function kill() public {
require(msg.sender == sysAdminAddress,"You can't do this");
require(roundNumber>=10,"Wait patiently");
bool noPlayer;
//Check if users have participated in the last 10 rounds
for(uint256 i=0;i<10;i++) {
uint256 eth = rInfoXrID[roundNumber-i].increaseETH;
if(eth == 0) {
noPlayer = true;
} else {
noPlayer = false;
}
}
require(noPlayer,"This cannot be done because the user is still present");
uint256 p3dBalance = p3dContract.balanceOf(address(this));
p3dContract.transfer(sysAdminAddress,p3dBalance);
sysAdminAddress.transfer(address(this).balance);
selfdestruct(sysAdminAddress);
}
//********************
// Calculate Data
//********************
function getBounsWithRoundID(uint256 _roundID) private view returns(uint256 _bouns) {
_bouns = _bouns.add(rInfoXrID[_roundID].bounsInitNumber).add(rInfoXrID[_roundID].increaseETH);
return(_bouns);
}
function getETHNeedPay(uint256 _roundID,uint256 _dayID) private view returns(uint256 _amount) {
if(_dayID >=2) {
uint256 mineTotal = rInfoXrID[_roundID].totalMine.sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].actualMine).sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].increaseMine);
_amount = mineTotal.mul(getTransformRate()).div(10000);
} else {
_amount = 0;
}
return(_amount);
}
function getIncreaseBalance(uint256 _dayID,uint256 _roundID) private view returns(uint256 _balance) {
_balance = rInfoXrID[_roundID].dayInfoXDay[_dayID].increaseETH;
return(_balance);
}
function getMineInfoInDay(address _userAddress,uint256 _roundID, uint256 _dayID) private view returns(uint256 _totalMine,uint256 _myMine,uint256 _additional) {
//Through traversal, the total amount of ore by the end of the day, the amount of ore held by users, and the amount of additional additional secondary ore
for(uint256 i=1;i<=_dayID;i++) {
if(rInfoXrID[_roundID].increaseETH == 0) return(0,0,0);
uint256 userActualMine = rInfoXrID[_roundID].dayInfoXDay[i].mineAmountXAddress[_userAddress];
uint256 increaseMineInDay = rInfoXrID[_roundID].dayInfoXDay[i].increaseMine;
_myMine = _myMine.add(userActualMine);
_totalMine = _totalMine.add(rInfoXrID[_roundID].dayInfoXDay[i].increaseETH*50/9);
uint256 dividendsMine = _myMine.mul(increaseMineInDay).div(_totalMine);
_totalMine = _totalMine.add(increaseMineInDay);
_myMine = _myMine.add(dividendsMine);
_additional = dividendsMine;
}
return(_totalMine,_myMine,_additional);
}
//Ore ->eth conversion rate
function getTransformRate() private pure returns(uint256 _rate) {
return(60);
}
//Calculate the amount of eth to be paid in x day for user
function getTransformMineInDay(address _userAddress,uint256 _roundID,uint256 _dayID) private view returns(uint256 _transformedMine) {
(,uint256 userMine,) = getMineInfoInDay(_userAddress,_roundID,_dayID.sub(1));
uint256 rate = getTransformRate();
_transformedMine = userMine.mul(rate).div(10000);
return(_transformedMine);
}
//Calculate the amount of eth to be paid in x day for all people
function calculateTotalMinePay(uint256 _roundID,uint256 _dayID) private view returns(uint256 _needToPay) {
uint256 mine = rInfoXrID[_roundID].totalMine.sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].actualMine).sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].increaseMine);
_needToPay = mine.mul(getTransformRate()).div(10000);
return(_needToPay);
}
//Calculate daily target values
function getDailyTarget(uint256 _roundID,uint256 _dayID) private view returns(uint256) {
uint256 needToPay = calculateTotalMinePay(_roundID,_dayID);
uint256 target = 0;
if (_dayID > 33) {
target = (SafeMath.pwr(((3).mul(_dayID).sub(100)),3).mul(50).add(1000000)).mul(needToPay).div(1000000);
return(target);
} else {
target = ((1000000).sub(SafeMath.pwr((100).sub((3).mul(_dayID)),3))).mul(needToPay).div(1000000);
if(target == 0) target = 0.0063 ether;
return(target);
}
}
//Query user income balance
function getUserBalance(address _userAddress) private view returns(uint256 _balance) {
if(pIDXpAdd[_userAddress] == 0) {
return(0);
}
//Amount of user withdrawal
uint256 withDrawNumber = pInfoXpAdd[_userAddress].withDrawNumber;
uint256 totalTransformed = 0;
//Calculate the number of ETH users get through the daily conversion
bool islocked = checkContructIsLocked();
for(uint256 i=1;i<=roundNumber;i++) {
if(islocked && i == roundNumber) {
return;
}
for(uint256 j=1;j<rInfoXrID[i].totalDay;j++) {
totalTransformed = totalTransformed.add(getTransformMineInDay(_userAddress,i,j));
}
}
//Get the ETH obtained by user invitation
uint256 inviteEarnings = pInfoXpAdd[_userAddress].inviteEarnings;
_balance = totalTransformed.add(inviteEarnings).add(getBounsEarnings(_userAddress)).add(getHoldEarnings(_userAddress)).add(getUserP3DDivEarnings(_userAddress)).sub(withDrawNumber);
return(_balance);
}
//calculate how much eth user have paid
function getUserPayedInCurrentRound(address _userAddress) public view returns(uint256 _payAmount) {
if(pInfoXpAdd[_userAddress].getPaidETHBackXRoundID[roundNumber]) {
return(0);
}
for(uint256 i=1;i<=rInfoXrID[roundNumber].totalDay;i++) {
_payAmount = _payAmount.add(rInfoXrID[roundNumber].dayInfoXDay[i].ethPayAmountXAddress[_userAddress]);
}
return(_payAmount);
}
//user can get eth back if the contract is locked
function getPaidETHBack() public {
require(checkContructIsLocked(),"The contract is in normal operation");
address _sender = msg.sender;
uint256 paidAmount = getUserPayedInCurrentRound(_sender);
pInfoXpAdd[_sender].getPaidETHBackXRoundID[roundNumber] = true;
_sender.transfer(paidAmount);
}
//Calculated the number of ETH users won in the prize pool
function getBounsEarnings(address _userAddress) private view returns(uint256 _bounsEarnings) {
for(uint256 i=1;i<roundNumber;i++) {
uint256 winnerDay = rInfoXrID[i].winnerDay;
uint256 myAmountInWinnerDay=rInfoXrID[i].dayInfoXDay[winnerDay].ethPayAmountXAddress[_userAddress];
uint256 totalAmountInWinnerDay=rInfoXrID[i].dayInfoXDay[winnerDay].increaseETH*10/9;
if(winnerDay == 0) {
_bounsEarnings = _bounsEarnings;
} else {
uint256 bouns = getBounsWithRoundID(i).mul(14).div(25);
_bounsEarnings = _bounsEarnings.add(bouns.mul(myAmountInWinnerDay).div(totalAmountInWinnerDay));
}
}
return(_bounsEarnings);
}
//Compute the ETH that the user acquires by holding the ore
function getHoldEarnings(address _userAddress) private view returns(uint256 _holdEarnings) {
for(uint256 i=1;i<roundNumber;i++) {
uint256 winnerDay = rInfoXrID[i].winnerDay;
if(winnerDay == 0) {
_holdEarnings = _holdEarnings;
} else {
(uint256 totalMine,uint256 myMine,) = getMineInfoInDay(_userAddress,i,rInfoXrID[i].totalDay);
uint256 bouns = getBounsWithRoundID(i).mul(7).div(50);
_holdEarnings = _holdEarnings.add(bouns.mul(myMine).div(totalMine));
}
}
return(_holdEarnings);
}
//Calculate user's P3D bonus
function getUserP3DDivEarnings(address _userAddress) private view returns(uint256 _myP3DDivide) {
if(rInfoXrID[roundNumber].totalDay <= 1) {
return(0);
}
for(uint256 i=1;i<roundNumber;i++) {
uint256 p3dDay = rInfoXrID[i].totalDay;
uint256 myAmountInp3dDay=rInfoXrID[i].dayInfoXDay[p3dDay].ethPayAmountXAddress[_userAddress];
uint256 totalAmountInP3dDay=rInfoXrID[i].dayInfoXDay[p3dDay].increaseETH*10/9;
if(p3dDay == 0) {
_myP3DDivide = _myP3DDivide;
} else {
uint256 p3dDividesInRound = p3dDividesXroundID[i];
_myP3DDivide = _myP3DDivide.add(p3dDividesInRound.mul(myAmountInp3dDay).div(totalAmountInP3dDay));
}
}
return(_myP3DDivide);
}
//*******************
// Check contract lock
//*******************
function checkContructIsLocked() public view returns(bool) {
uint256 time = now.sub(rInfoXrID[roundNumber].lastCalculateTime);
if(time >= 2*cycleTime) {
return(true);
} else {
return(false);
}
}
//*******************
// UI
//*******************
function getDefendPlayerList() public view returns(address[]) {
if (rInfoXrID[roundNumber].dayInfoXDay[dayNumber-1].playerNumber == 0) {
address[] memory playerListEmpty = new address[](0);
return(playerListEmpty);
}
uint256 number = rInfoXrID[roundNumber].dayInfoXDay[dayNumber-1].playerNumber;
if(number > 100) {
number == 100;
}
address[] memory playerList = new address[](number);
for(uint256 i=0;i<number;i++) {
playerList[i] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber-1].addXIndex[i+1];
}
return(playerList);
}
function getAttackPlayerList() public view returns(address[]) {
uint256 number = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber;
if(number > 100) {
number == 100;
}
address[] memory playerList = new address[](number);
for(uint256 i=0;i<number;i++) {
playerList[i] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].addXIndex[i+1];
}
return(playerList);
}
function getCurrentFieldBalanceAndTarget() public view returns(uint256 day,uint256 bouns,uint256 todayBouns,uint256 dailyTarget) {
uint256 fieldBalance = getBounsWithRoundID(roundNumber).mul(7).div(10);
uint256 todayBalance = getIncreaseBalance(dayNumber,roundNumber) ;
dailyTarget = getDailyTarget(roundNumber,dayNumber);
return(dayNumber,fieldBalance,todayBalance,dailyTarget);
}
function getUserIDAndInviterEarnings() public view returns(uint256 userID,uint256 inviteEarning) {
return(pIDXpAdd[msg.sender],pInfoXpAdd[msg.sender].inviteEarnings);
}
function getCurrentRoundInfo() public view returns(uint256 _roundID,uint256 _dayNumber,uint256 _ethMineNumber,uint256 _startTime,uint256 _lastCalculateTime) {
DataModal.RoundInfo memory roundInfo = rInfoXrID[roundNumber];
(uint256 totalMine,,) = getMineInfoInDay(msg.sender,roundNumber,dayNumber);
return(roundNumber,dayNumber,totalMine,roundInfo.startTime,roundInfo.lastCalculateTime);
}
function getUserProperty() public view returns(uint256 ethMineNumber,uint256 holdEarning,uint256 transformRate,uint256 ethBalance,uint256 ethTranslated,uint256 ethMineCouldTranslateToday,uint256 ethCouldGetToday) {
if(pIDXpAdd[msg.sender] <1) {
return(0,0,0,0,0,0,0);
}
(,uint256 myMine,uint256 additional) = getMineInfoInDay(msg.sender,roundNumber,dayNumber);
ethMineNumber = myMine;
holdEarning = additional;
transformRate = getTransformRate();
ethBalance = getUserBalance(msg.sender);
uint256 totalTransformed = 0;
for(uint256 i=1;i<rInfoXrID[roundNumber].totalDay;i++) {
totalTransformed = totalTransformed.add(getTransformMineInDay(msg.sender,roundNumber,i));
}
ethTranslated = totalTransformed;
ethCouldGetToday = getTransformMineInDay(msg.sender,roundNumber,dayNumber);
ethMineCouldTranslateToday = myMine.mul(transformRate).div(10000);
return(
ethMineNumber,
holdEarning,
transformRate,
ethBalance,
ethTranslated,
ethMineCouldTranslateToday,
ethCouldGetToday
);
}
function getPlatformBalance() public view returns(uint256 _platformBalance) {
require(msg.sender == sysAdminAddress,"Ummmmm......Only admin could do this");
return(platformBalance);
}
//************
// for statistics
//************
function getDataOfGame() public view returns(uint256 _playerNumber,uint256 _dailyIncreased,uint256 _dailyTransform,uint256 _contractBalance,uint256 _userBalanceLeft,uint256 _platformBalance,uint256 _mineBalance,uint256 _balanceOfMine) {
for(uint256 i=1;i<=totalPlayerNumber;i++) {
address userAddress = pAddXpID[i];
_userBalanceLeft = _userBalanceLeft.add(getUserBalance(userAddress));
}
return(
totalPlayerNumber,
getIncreaseBalance(dayNumber,roundNumber),
calculateTotalMinePay(roundNumber,dayNumber),
address(this).balance,
_userBalanceLeft,
platformBalance,
getBounsWithRoundID(roundNumber),
getBounsWithRoundID(roundNumber).mul(7).div(10)
);
}
function getUserAddressList() public view returns(address[]) {
address[] memory addressList = new address[](totalPlayerNumber);
for(uint256 i=0;i<totalPlayerNumber;i++) {
addressList[i] = pAddXpID[i+1];
}
return(addressList);
}
function getUsersInfo() public view returns(uint256[7][]){
uint256[7][] memory infoList = new uint256[7][](totalPlayerNumber);
for(uint256 i=0;i<totalPlayerNumber;i++) {
address userAddress = pAddXpID[i+1];
(,uint256 myMine,uint256 additional) = getMineInfoInDay(userAddress,roundNumber,dayNumber);
uint256 totalTransformed = 0;
for(uint256 j=1;j<=roundNumber;j++) {
for(uint256 k=1;k<=rInfoXrID[j].totalDay;k++) {
totalTransformed = totalTransformed.add(getTransformMineInDay(userAddress,j,k));
}
}
infoList[i][0] = myMine ;
infoList[i][1] = getTransformRate();
infoList[i][2] = additional;
infoList[i][3] = getUserBalance(userAddress);
infoList[i][4] = getUserBalance(userAddress).add(pInfoXpAdd[userAddress].withDrawNumber);
infoList[i][5] = pInfoXpAdd[userAddress].inviteEarnings;
infoList[i][6] = totalTransformed;
}
return(infoList);
}
function getP3DInfo() public view returns(uint256 _p3dTokenInContract,uint256 _p3dDivInRound) {
_p3dTokenInContract = p3dContract.balanceOf(address(this));
_p3dDivInRound = p3dDividesXroundID[roundNumber];
return(_p3dTokenInContract,_p3dDivInRound);
}
}
//P3D Interface
interface HourglassInterface {
function buy(address _playerAddress) payable external returns(uint256);
function withdraw() external;
function myDividends(bool _includeReferralBonus) external view returns(uint256);
function balanceOf(address _customerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
}
library DataModal {
struct PlayerInfo {
uint256 inviteEarnings;
address inviterAddress;
uint256 withDrawNumber;
mapping(uint256=>bool) getPaidETHBackXRoundID;
}
struct DayInfo {
uint256 playerNumber;
uint256 actualMine;
uint256 increaseETH;
uint256 increaseMine;
mapping(uint256=>address) addXIndex;
mapping(address=>uint256) ethPayAmountXAddress;
mapping(address=>uint256) mineAmountXAddress;
}
struct RoundInfo {
uint256 startTime;
uint256 lastCalculateTime;
uint256 bounsInitNumber;
uint256 increaseETH;
uint256 totalDay;
uint256 winnerDay;
uint256 totalMine;
mapping(uint256=>DayInfo) dayInfoXDay;
}
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath div failed");
uint256 c = a / b;
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);
}
}
} | Through traversal, the total amount of ore by the end of the day, the amount of ore held by users, and the amount of additional additional secondary ore | function getMineInfoInDay(address _userAddress,uint256 _roundID, uint256 _dayID) private view returns(uint256 _totalMine,uint256 _myMine,uint256 _additional) {
for(uint256 i=1;i<=_dayID;i++) {
if(rInfoXrID[_roundID].increaseETH == 0) return(0,0,0);
uint256 userActualMine = rInfoXrID[_roundID].dayInfoXDay[i].mineAmountXAddress[_userAddress];
uint256 increaseMineInDay = rInfoXrID[_roundID].dayInfoXDay[i].increaseMine;
_myMine = _myMine.add(userActualMine);
_totalMine = _totalMine.add(rInfoXrID[_roundID].dayInfoXDay[i].increaseETH*50/9);
uint256 dividendsMine = _myMine.mul(increaseMineInDay).div(_totalMine);
_totalMine = _totalMine.add(increaseMineInDay);
_myMine = _myMine.add(dividendsMine);
_additional = dividendsMine;
}
return(_totalMine,_myMine,_additional);
}
| 12,547,010 |
// $$\ $$\ $$\ $$$$$$$\ $$\
// $$ | $$ | $$ | $$ __$$\ $$ |
// $$ | $$ |$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$$\ $$ | $$ | $$$$$$\ $$$$$$\ $$ |
// $$$$$$$$ |$$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ $$$$$$$ |$$ __$$\ $$ __$$\ $$ |
// $$ __$$ |$$ | $$ |$$ / $$ |$$ | $$ |$$$$$$$$ |$$ | $$ | $$ ____/ $$ / $$ |$$ / $$ |$$ |
// $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ ____|$$ | $$ | $$ | $$ | $$ |$$ | $$ |$$ |
// $$ | $$ |\$$$$$$$ |$$$$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ | $$ | \$$$$$$ |\$$$$$$ |$$ |
// \__| \__| \____$$ |$$ ____/ \__| \__| \_______|\__| \__| \__| \______/ \______/ \__|
// $$\ $$ |$$ |
// \$$$$$$ |$$ |
// \______/ \__|
//
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./metatx/ERC2771ContextUpgradeable.sol";
import "../security/Pausable.sol";
import "./structures/TokenConfig.sol";
import "./interfaces/IExecutorManager.sol";
import "./interfaces/ILiquidityProviders.sol";
import "../interfaces/IERC20Permit.sol";
import "./interfaces/ITokenManager.sol";
contract LiquidityPool is
Initializable,
ReentrancyGuardUpgradeable,
Pausable,
OwnableUpgradeable,
ERC2771ContextUpgradeable
{
address private constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 private constant BASE_DIVISOR = 10000000000; // Basis Points * 100 for better accuracy
uint256 public baseGas;
IExecutorManager private executorManager;
ITokenManager public tokenManager;
ILiquidityProviders public liquidityProviders;
struct PermitRequest {
uint256 nonce;
uint256 expiry;
bool allowed;
uint8 v;
bytes32 r;
bytes32 s;
}
mapping(bytes32 => bool) public processedHash;
mapping(address => uint256) public gasFeeAccumulatedByToken;
// Gas fee accumulated by token address => executor address
mapping(address => mapping(address => uint256)) public gasFeeAccumulated;
// Incentive Pool amount per token address
mapping(address => uint256) public incentivePool;
event AssetSent(
address indexed asset,
uint256 indexed amount,
uint256 indexed transferredAmount,
address target,
bytes depositHash,
uint256 fromChainId,
uint256 lpFee,
uint256 transferFee,
uint256 gasFee
);
event Received(address indexed from, uint256 indexed amount);
event Deposit(
address indexed from,
address indexed tokenAddress,
address indexed receiver,
uint256 toChainId,
uint256 amount,
uint256 reward,
string tag
);
event GasFeeWithdraw(address indexed tokenAddress, address indexed owner, uint256 indexed amount);
event LiquidityProvidersChanged(address indexed liquidityProvidersAddress);
event TokenManagerChanged(address indexed tokenManagerAddress);
event BaseGasUpdated(uint256 indexed baseGas);
event EthReceived(address, uint256);
// MODIFIERS
modifier onlyExecutor() {
require(executorManager.getExecutorStatus(_msgSender()), "Only executor is allowed");
_;
}
modifier onlyLiquidityProviders() {
require(_msgSender() == address(liquidityProviders), "Only liquidityProviders is allowed");
_;
}
modifier tokenChecks(address tokenAddress) {
(, bool supportedToken, , , ) = tokenManager.tokensInfo(tokenAddress);
require(supportedToken, "Token not supported");
_;
}
function initialize(
address _executorManagerAddress,
address _pauser,
address _trustedForwarder,
address _tokenManager,
address _liquidityProviders
) public initializer {
require(_executorManagerAddress != address(0), "ExecutorManager cannot be 0x0");
require(_trustedForwarder != address(0), "TrustedForwarder cannot be 0x0");
require(_liquidityProviders != address(0), "LiquidityProviders cannot be 0x0");
__ERC2771Context_init(_trustedForwarder);
__ReentrancyGuard_init();
__Ownable_init();
__Pausable_init(_pauser);
executorManager = IExecutorManager(_executorManagerAddress);
tokenManager = ITokenManager(_tokenManager);
liquidityProviders = ILiquidityProviders(_liquidityProviders);
baseGas = 21000;
}
function setTrustedForwarder(address trustedForwarder) external onlyOwner {
_setTrustedForwarder(trustedForwarder);
}
function setLiquidityProviders(address _liquidityProviders) external onlyOwner {
require(_liquidityProviders != address(0), "LiquidityProviders can't be 0");
liquidityProviders = ILiquidityProviders(_liquidityProviders);
emit LiquidityProvidersChanged(_liquidityProviders);
}
function setTokenManager(address _tokenManager) external onlyOwner {
require(_tokenManager != address(0), "TokenManager can't be 0");
tokenManager = ITokenManager(_tokenManager);
emit TokenManagerChanged(_tokenManager);
}
function setBaseGas(uint128 gas) external onlyOwner {
baseGas = gas;
emit BaseGasUpdated(baseGas);
}
function getExecutorManager() external view returns (address) {
return address(executorManager);
}
function setExecutorManager(address _executorManagerAddress) external onlyOwner {
require(_executorManagerAddress != address(0), "Executor Manager cannot be 0");
executorManager = IExecutorManager(_executorManagerAddress);
}
function getCurrentLiquidity(address tokenAddress) public view returns (uint256 currentLiquidity) {
uint256 liquidityPoolBalance = liquidityProviders.getCurrentLiquidity(tokenAddress);
currentLiquidity =
liquidityPoolBalance -
liquidityProviders.totalLPFees(tokenAddress) -
gasFeeAccumulatedByToken[tokenAddress] -
incentivePool[tokenAddress];
}
/**
* @dev Function used to deposit tokens into pool to initiate a cross chain token transfer.
* @param toChainId Chain id where funds needs to be transfered
* @param tokenAddress ERC20 Token address that needs to be transfered
* @param receiver Address on toChainId where tokens needs to be transfered
* @param amount Amount of token being transfered
*/
function depositErc20(
uint256 toChainId,
address tokenAddress,
address receiver,
uint256 amount,
string calldata tag
) public tokenChecks(tokenAddress) whenNotPaused nonReentrant {
require(toChainId != block.chainid, "To chain must be different than current chain");
require(tokenAddress != NATIVE, "wrong function");
TokenConfig memory config = tokenManager.getDepositConfig(toChainId, tokenAddress);
require(config.min <= amount && config.max >= amount, "Deposit amount not in Cap limit");
require(receiver != address(0), "Receiver address cannot be 0");
require(amount != 0, "Amount cannot be 0");
address sender = _msgSender();
uint256 rewardAmount = getRewardAmount(amount, tokenAddress);
if (rewardAmount != 0) {
incentivePool[tokenAddress] = incentivePool[tokenAddress] - rewardAmount;
}
liquidityProviders.increaseCurrentLiquidity(tokenAddress, amount);
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(tokenAddress), sender, address(this), amount);
// Emit (amount + reward amount) in event
emit Deposit(sender, tokenAddress, receiver, toChainId, amount + rewardAmount, rewardAmount, tag);
}
function getRewardAmount(uint256 amount, address tokenAddress) public view returns (uint256 rewardAmount) {
uint256 currentLiquidity = getCurrentLiquidity(tokenAddress);
uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress);
if (currentLiquidity < providedLiquidity) {
uint256 liquidityDifference = providedLiquidity - currentLiquidity;
if (amount >= liquidityDifference) {
rewardAmount = incentivePool[tokenAddress];
} else {
// Multiply by 10000000000 to avoid 0 reward amount for small amount and liquidity difference
rewardAmount = (amount * incentivePool[tokenAddress] * 10000000000) / liquidityDifference;
rewardAmount = rewardAmount / 10000000000;
}
}
}
/**
* DAI permit and Deposit.
*/
function permitAndDepositErc20(
address tokenAddress,
address receiver,
uint256 amount,
uint256 toChainId,
PermitRequest calldata permitOptions,
string calldata tag
) external {
IERC20Permit(tokenAddress).permit(
_msgSender(),
address(this),
permitOptions.nonce,
permitOptions.expiry,
permitOptions.allowed,
permitOptions.v,
permitOptions.r,
permitOptions.s
);
depositErc20(toChainId, tokenAddress, receiver, amount, tag);
}
/**
* EIP2612 and Deposit.
*/
function permitEIP2612AndDepositErc20(
address tokenAddress,
address receiver,
uint256 amount,
uint256 toChainId,
PermitRequest calldata permitOptions,
string calldata tag
) external {
IERC20Permit(tokenAddress).permit(
_msgSender(),
address(this),
amount,
permitOptions.expiry,
permitOptions.v,
permitOptions.r,
permitOptions.s
);
depositErc20(toChainId, tokenAddress, receiver, amount, tag);
}
/**
* @dev Function used to deposit native token into pool to initiate a cross chain token transfer.
* @param receiver Address on toChainId where tokens needs to be transfered
* @param toChainId Chain id where funds needs to be transfered
*/
function depositNative(
address receiver,
uint256 toChainId,
string calldata tag
) external payable whenNotPaused nonReentrant {
require(toChainId != block.chainid, "To chain must be different than current chain");
require(
tokenManager.getDepositConfig(toChainId, NATIVE).min <= msg.value &&
tokenManager.getDepositConfig(toChainId, NATIVE).max >= msg.value,
"Deposit amount not in Cap limit"
);
require(receiver != address(0), "Receiver address cannot be 0");
require(msg.value != 0, "Amount cannot be 0");
uint256 rewardAmount = getRewardAmount(msg.value, NATIVE);
if (rewardAmount != 0) {
incentivePool[NATIVE] = incentivePool[NATIVE] - rewardAmount;
}
liquidityProviders.increaseCurrentLiquidity(NATIVE, msg.value);
emit Deposit(_msgSender(), NATIVE, receiver, toChainId, msg.value + rewardAmount, rewardAmount, tag);
}
function sendFundsToUser(
address tokenAddress,
uint256 amount,
address payable receiver,
bytes calldata depositHash,
uint256 tokenGasPrice,
uint256 fromChainId
) external nonReentrant onlyExecutor whenNotPaused {
uint256 initialGas = gasleft();
TokenConfig memory config = tokenManager.getTransferConfig(tokenAddress);
require(config.min <= amount && config.max >= amount, "Withdraw amount not in Cap limit");
require(receiver != address(0), "Bad receiver address");
(bytes32 hashSendTransaction, bool status) = checkHashStatus(tokenAddress, amount, receiver, depositHash);
require(!status, "Already Processed");
processedHash[hashSendTransaction] = true;
// uint256 amountToTransfer, uint256 lpFee, uint256 transferFeeAmount, uint256 gasFee
uint256[4] memory transferDetails = getAmountToTransfer(initialGas, tokenAddress, amount, tokenGasPrice);
liquidityProviders.decreaseCurrentLiquidity(tokenAddress, transferDetails[0]);
if (tokenAddress == NATIVE) {
(bool success, ) = receiver.call{value: transferDetails[0]}("");
require(success, "Native Transfer Failed");
} else {
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), receiver, transferDetails[0]);
}
emit AssetSent(
tokenAddress,
amount,
transferDetails[0],
receiver,
depositHash,
fromChainId,
transferDetails[1],
transferDetails[2],
transferDetails[3]
);
}
/**
* @dev Internal function to calculate amount of token that needs to be transfered afetr deducting all required fees.
* Fee to be deducted includes gas fee, lp fee and incentive pool amount if needed.
* @param initialGas Gas provided initially before any calculations began
* @param tokenAddress Token address for which calculation needs to be done
* @param amount Amount of token to be transfered before deducting the fee
* @param tokenGasPrice Gas price in the token being transfered to be used to calculate gas fee
* @return [ amountToTransfer, lpFee, transferFeeAmount, gasFee ]
*/
function getAmountToTransfer(
uint256 initialGas,
address tokenAddress,
uint256 amount,
uint256 tokenGasPrice
) internal returns (uint256[4] memory) {
TokenInfo memory tokenInfo = tokenManager.getTokensInfo(tokenAddress);
uint256 transferFeePerc = _getTransferFee(tokenAddress, amount, tokenInfo);
uint256 lpFee;
if (transferFeePerc > tokenInfo.equilibriumFee) {
// Here add some fee to incentive pool also
lpFee = (amount * tokenInfo.equilibriumFee) / BASE_DIVISOR;
unchecked {
incentivePool[tokenAddress] += (amount * (transferFeePerc - tokenInfo.equilibriumFee)) / BASE_DIVISOR;
}
} else {
lpFee = (amount * transferFeePerc) / BASE_DIVISOR;
}
uint256 transferFeeAmount = (amount * transferFeePerc) / BASE_DIVISOR;
liquidityProviders.addLPFee(tokenAddress, lpFee);
uint256 totalGasUsed = initialGas + tokenInfo.transferOverhead + baseGas - gasleft();
uint256 gasFee = totalGasUsed * tokenGasPrice;
gasFeeAccumulatedByToken[tokenAddress] += gasFee;
gasFeeAccumulated[tokenAddress][_msgSender()] += gasFee;
uint256 amountToTransfer = amount - (transferFeeAmount + gasFee);
return [amountToTransfer, lpFee, transferFeeAmount, gasFee];
}
function sendFundsToUserV2(
address tokenAddress,
uint256 amount,
address payable receiver,
bytes calldata depositHash,
uint256 nativeTokenPriceInTransferredToken,
uint256 fromChainId
) external nonReentrant onlyExecutor whenNotPaused {
uint256 initialGas = gasleft();
TokenConfig memory config = tokenManager.getTransferConfig(tokenAddress);
require(config.min <= amount && config.max >= amount, "Withdraw amount not in Cap limit");
require(receiver != address(0), "Bad receiver address");
(bytes32 hashSendTransaction, bool status) = checkHashStatus(tokenAddress, amount, receiver, depositHash);
require(!status, "Already Processed");
processedHash[hashSendTransaction] = true;
// uint256 amountToTransfer, uint256 lpFee, uint256 transferFeeAmount, uint256 gasFee
uint256[4] memory transferDetails = getAmountToTransferV2(
initialGas,
tokenAddress,
amount,
nativeTokenPriceInTransferredToken
);
liquidityProviders.decreaseCurrentLiquidity(tokenAddress, transferDetails[0]);
if (tokenAddress == NATIVE) {
(bool success, ) = receiver.call{value: transferDetails[0]}("");
require(success, "Native Transfer Failed");
} else {
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), receiver, transferDetails[0]);
}
emit AssetSent(
tokenAddress,
amount,
transferDetails[0],
receiver,
depositHash,
fromChainId,
transferDetails[1],
transferDetails[2],
transferDetails[3]
);
}
/**
* @dev Internal function to calculate amount of token that needs to be transfered afetr deducting all required fees.
* Fee to be deducted includes gas fee, lp fee and incentive pool amount if needed.
* @param initialGas Gas provided initially before any calculations began
* @param tokenAddress Token address for which calculation needs to be done
* @param amount Amount of token to be transfered before deducting the fee
* @param nativeTokenPriceInTransferredToken Price of native token in terms of the token being transferred (multiplied base div), used to calculate gas fee
* @return [ amountToTransfer, lpFee, transferFeeAmount, gasFee ]
*/
function getAmountToTransferV2(
uint256 initialGas,
address tokenAddress,
uint256 amount,
uint256 nativeTokenPriceInTransferredToken
) internal returns (uint256[4] memory) {
TokenInfo memory tokenInfo = tokenManager.getTokensInfo(tokenAddress);
uint256 transferFeePerc = _getTransferFee(tokenAddress, amount, tokenInfo);
uint256 lpFee;
if (transferFeePerc > tokenInfo.equilibriumFee) {
// Here add some fee to incentive pool also
lpFee = (amount * tokenInfo.equilibriumFee) / BASE_DIVISOR;
unchecked {
incentivePool[tokenAddress] += (amount * (transferFeePerc - tokenInfo.equilibriumFee)) / BASE_DIVISOR;
}
} else {
lpFee = (amount * transferFeePerc) / BASE_DIVISOR;
}
uint256 transferFeeAmount = (amount * transferFeePerc) / BASE_DIVISOR;
liquidityProviders.addLPFee(tokenAddress, lpFee);
uint256 totalGasUsed = initialGas + tokenInfo.transferOverhead + baseGas - gasleft();
uint256 gasFee = (totalGasUsed * nativeTokenPriceInTransferredToken * tx.gasprice) / BASE_DIVISOR;
gasFeeAccumulatedByToken[tokenAddress] += gasFee;
gasFeeAccumulated[tokenAddress][_msgSender()] += gasFee;
uint256 amountToTransfer = amount - (transferFeeAmount + gasFee);
return [amountToTransfer, lpFee, transferFeeAmount, gasFee];
}
function _getTransferFee(
address tokenAddress,
uint256 amount,
TokenInfo memory tokenInfo
) private view returns (uint256) {
uint256 currentLiquidity = getCurrentLiquidity(tokenAddress);
uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress);
uint256 resultingLiquidity = currentLiquidity - amount;
// We return a constant value in excess state
if (resultingLiquidity > providedLiquidity) {
return tokenManager.excessStateTransferFeePerc(tokenAddress);
}
// Fee is represented in basis points * 10 for better accuracy
uint256 numerator = providedLiquidity * providedLiquidity * tokenInfo.equilibriumFee * tokenInfo.maxFee; // F(max) * F(e) * L(e) ^ 2
uint256 denominator = tokenInfo.equilibriumFee *
providedLiquidity *
providedLiquidity +
(tokenInfo.maxFee - tokenInfo.equilibriumFee) *
resultingLiquidity *
resultingLiquidity; // F(e) * L(e) ^ 2 + (F(max) - F(e)) * L(r) ^ 2
uint256 fee;
if (denominator == 0) {
fee = 0;
} else {
fee = numerator / denominator;
}
return fee;
}
function getTransferFee(address tokenAddress, uint256 amount) external view returns (uint256) {
return _getTransferFee(tokenAddress, amount, tokenManager.getTokensInfo(tokenAddress));
}
function checkHashStatus(
address tokenAddress,
uint256 amount,
address payable receiver,
bytes calldata depositHash
) public view returns (bytes32 hashSendTransaction, bool status) {
hashSendTransaction = keccak256(abi.encode(tokenAddress, amount, receiver, keccak256(depositHash)));
status = processedHash[hashSendTransaction];
}
function withdrawErc20GasFee(address tokenAddress) external onlyExecutor whenNotPaused nonReentrant {
require(tokenAddress != NATIVE, "Can't withdraw native token fee");
// uint256 gasFeeAccumulated = gasFeeAccumulatedByToken[tokenAddress];
uint256 _gasFeeAccumulated = gasFeeAccumulated[tokenAddress][_msgSender()];
require(_gasFeeAccumulated != 0, "Gas Fee earned is 0");
gasFeeAccumulatedByToken[tokenAddress] = gasFeeAccumulatedByToken[tokenAddress] - _gasFeeAccumulated;
gasFeeAccumulated[tokenAddress][_msgSender()] = 0;
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), _msgSender(), _gasFeeAccumulated);
emit GasFeeWithdraw(tokenAddress, _msgSender(), _gasFeeAccumulated);
}
function withdrawNativeGasFee() external onlyExecutor whenNotPaused nonReentrant {
uint256 _gasFeeAccumulated = gasFeeAccumulated[NATIVE][_msgSender()];
require(_gasFeeAccumulated != 0, "Gas Fee earned is 0");
gasFeeAccumulatedByToken[NATIVE] = gasFeeAccumulatedByToken[NATIVE] - _gasFeeAccumulated;
gasFeeAccumulated[NATIVE][_msgSender()] = 0;
(bool success, ) = payable(_msgSender()).call{value: _gasFeeAccumulated}("");
require(success, "Native Transfer Failed");
emit GasFeeWithdraw(address(this), _msgSender(), _gasFeeAccumulated);
}
function transfer(
address _tokenAddress,
address receiver,
uint256 _tokenAmount
) external whenNotPaused onlyLiquidityProviders nonReentrant {
require(receiver != address(0), "Invalid receiver");
if (_tokenAddress == NATIVE) {
require(address(this).balance >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE");
(bool success, ) = receiver.call{value: _tokenAmount}("");
require(success, "ERR__NATIVE_TRANSFER_FAILED");
} else {
IERC20Upgradeable baseToken = IERC20Upgradeable(_tokenAddress);
require(baseToken.balanceOf(address(this)) >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE");
SafeERC20Upgradeable.safeTransfer(baseToken, receiver, _tokenAmount);
}
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
receive() external payable {
emit EthReceived(_msgSender(), msg.value);
}
}
| Internal function to calculate amount of token that needs to be transfered afetr deducting all required fees. Fee to be deducted includes gas fee, lp fee and incentive pool amount if needed. initialGas Gas provided initially before any calculations began tokenAddress Token address for which calculation needs to be done amount Amount of token to be transfered before deducting the fee nativeTokenPriceInTransferredToken Price of native token in terms of the token being transferred (multiplied base div), used to calculate gas fee return [ amountToTransfer, lpFee, transferFeeAmount, gasFee ]/ Here add some fee to incentive pool also | function getAmountToTransferV2(
uint256 initialGas,
address tokenAddress,
uint256 amount,
uint256 nativeTokenPriceInTransferredToken
) internal returns (uint256[4] memory) {
TokenInfo memory tokenInfo = tokenManager.getTokensInfo(tokenAddress);
uint256 transferFeePerc = _getTransferFee(tokenAddress, amount, tokenInfo);
uint256 lpFee;
if (transferFeePerc > tokenInfo.equilibriumFee) {
lpFee = (amount * tokenInfo.equilibriumFee) / BASE_DIVISOR;
unchecked {
incentivePool[tokenAddress] += (amount * (transferFeePerc - tokenInfo.equilibriumFee)) / BASE_DIVISOR;
}
lpFee = (amount * transferFeePerc) / BASE_DIVISOR;
}
uint256 transferFeeAmount = (amount * transferFeePerc) / BASE_DIVISOR;
liquidityProviders.addLPFee(tokenAddress, lpFee);
uint256 totalGasUsed = initialGas + tokenInfo.transferOverhead + baseGas - gasleft();
uint256 gasFee = (totalGasUsed * nativeTokenPriceInTransferredToken * tx.gasprice) / BASE_DIVISOR;
gasFeeAccumulatedByToken[tokenAddress] += gasFee;
gasFeeAccumulated[tokenAddress][_msgSender()] += gasFee;
uint256 amountToTransfer = amount - (transferFeeAmount + gasFee);
return [amountToTransfer, lpFee, transferFeeAmount, gasFee];
}
| 15,816,601 |
pragma solidity ^0.5.16;
contract ConstBase {
uint public constant C = 1;
function c() public pure returns (uint) {
return 1;
}
function ADD(uint a) public view returns (uint) {
// tells snkiler to accept view instead of pure
if (false) {
C + now;
}
return a + C;
}
function add(uint a) public view returns (uint) {
// tells snkiler to accept view instead of pure
if (false) {
C + now;
}
return a + c();
}
}
contract ConstSub is ConstBase {
function c() public pure returns (uint) {
return 2;
}
}
| tells snkiler to accept view instead of pure | function ADD(uint a) public view returns (uint) {
if (false) {
C + now;
}
return a + C;
}
| 12,785,594 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
// _setOwner(_msgSender());
_owner = 0x992Cd46dfE21377bef5A5178F8b8349de2C37453;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
interface IToken {
function transferOwnership(address newOwner) external;
function mint(address to, uint256 amount) external;
function burn(address owner, uint256 amount) external;
function transfer(address recipient, uint256 amount) external;
function transferFrom(
address sender,
address recipient,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 tokens)
external
returns (bool success);
}
abstract contract BridgeBase is Ownable{
address public validator;
IToken public token;
bool public whiteListOn;
mapping(address => bool) public isWhiteList;
mapping(bytes32 => bool) internal processedTransactions;
event TokenDeposit(
bytes32 txHash,
bytes transactionID
);
event TokenWithdraw(
address indexed from,
address indexed to,
uint256 amount,
uint256 nonce,
bytes sign
);
event WhiteListToggled(bool state);
event WhiteListAddressToggled(
address _user,
address _bridgeAddress,
bool _state
);
constructor(address _token, address _validator) {
require(_token != address(0), "Token cannot be 0 address");
require(_validator != address(0), "Admin cannot be 0 address");
token = IToken(_token);
validator = _validator;
whiteListOn = !whiteListOn;
}
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return recover(message, v, r, s);
}
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n / 2 + 1, and for v in (282): v in {27, 28 Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
function splitSignature(bytes memory sig)
internal
pure
returns (
uint8,
bytes32,
bytes32
)
{
require(sig.length == 65, "sig length invalid");
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function depositTokens(
uint256 amount,
address recipient
) external virtual;
function withdrawTokens(
bytes32 _txHash,
bytes calldata _transactionID,
bytes calldata signature
) external virtual;
function toggleWhiteListOnly() external onlyOwner {
//require(msg.sender == owner, "Sender not Owner");
whiteListOn = !whiteListOn;
emit WhiteListToggled(whiteListOn);
}
function toggleWhiteListAddress(address[] calldata _addresses)
external
onlyOwner
{
// require(msg.sender == owner, "Sender not Owner");
require(_addresses.length <= 200, "Addresses length exceeded");
for (uint256 i = 0; i < _addresses.length; i++) {
isWhiteList[_addresses[i]] = !isWhiteList[_addresses[i]];
emit WhiteListAddressToggled(
_addresses[i],
address(this),
isWhiteList[_addresses[i]]
);
}
}
}
contract ETHBridge is BridgeBase {
constructor(address token, address _validator) BridgeBase(token, _validator) {}
uint256 nonce_count;
function depositTokens(
uint256 amount,
address recipient
) external override {
require(
!whiteListOn || isWhiteList[msg.sender],
"ETHBridge: Forbidden in White List mode"
);
token.burn(msg.sender, amount);
nonce_count += 1;
bytes32 txHash = keccak256(abi.encode(amount, nonce_count, recipient, msg.sender));
bytes memory _transactionID = abi.encode(amount, nonce_count, recipient, msg.sender);
emit TokenDeposit(
txHash,
_transactionID
);
}
function withdrawTokens(
bytes32 _txHash,
bytes calldata _transactionID,
bytes calldata signature
) external override {
require(
!whiteListOn || isWhiteList[msg.sender],
"ETHBridge: Forbidden in White List mode"
);
(
uint256 _amount,
uint256 _nonce,
address _to,
address _from
) = abi.decode(_transactionID, (uint256, uint256, address, address));
require(msg.sender == _to, "ETHBridge: Irrelevant receiver");
address signAddress;
bytes32 message = prefixed(
keccak256(abi.encodePacked(_from, _to, _amount, _nonce))
);
signAddress = recoverSigner(message, signature);
require(validator == signAddress, "ETHBridge: wrong signature");
require(
!processedTransactions[_txHash],
"ETHBridge: transaction already processed"
);
processedTransactions[_txHash] = true;
token.mint(_to, _amount);
emit TokenWithdraw(_from, _to, _amount, _nonce, signature);
}
} | require(msg.sender == owner, "Sender not Owner"); | function toggleWhiteListAddress(address[] calldata _addresses)
external
onlyOwner
{
require(_addresses.length <= 200, "Addresses length exceeded");
for (uint256 i = 0; i < _addresses.length; i++) {
isWhiteList[_addresses[i]] = !isWhiteList[_addresses[i]];
emit WhiteListAddressToggled(
_addresses[i],
address(this),
isWhiteList[_addresses[i]]
);
}
}
| 12,108,576 |
./full_match/5/0xD6ee3B39dD53b753E3253Befa40222602406409B/sources/src/Vault.sol | Burn debt on a given vault vaultId Id of the vault amount The debt amount to be burned | function burnDebt(uint256 vaultId, uint256 amount) external {
_requireVaultOwner(vaultId);
_updateVaultStabilisationFee(vaultId);
uint256 currentVaultDebt = vaultDebt[vaultId];
uint256 overallDebt = stabilisationFeeVaultSnapshot[vaultId] + currentVaultDebt;
amount = (amount < overallDebt) ? amount : overallDebt;
uint256 overallAmount = amount;
if (amount > currentVaultDebt) {
uint256 burningFeeAmount = amount - currentVaultDebt;
token.mint(treasury, burningFeeAmount);
stabilisationFeeVaultSnapshot[vaultId] -= burningFeeAmount;
amount -= burningFeeAmount;
}
token.transferFrom(msg.sender, address(this), overallAmount);
token.burn(overallAmount);
vaultDebt[vaultId] -= amount;
emit DebtBurned(msg.sender, vaultId, overallAmount);
}
| 1,876,115 |
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/**
* @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);
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract IDollar is IERC20 {
function burn(uint256 amount) public;
function burnFrom(address account, uint256 amount) public;
function mint(address account, uint256 amount) public returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract IOracle {
function setup() public;
function capture() public returns (Decimal.D256 memory, bool);
function pair() external view returns (address);
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract Account {
enum Status {
Frozen,
Fluid,
Locked
}
struct State {
uint256 staged;
uint256 balance;
mapping(uint256 => uint256) coupons;
mapping(address => uint256) couponAllowances;
uint256 fluidUntil;
uint256 lockedUntil;
}
}
contract Epoch {
struct Global {
uint256 start;
uint256 period;
uint256 current;
}
struct Coupons {
uint256 outstanding;
uint256 expiration;
uint256[] expiring;
}
struct State {
uint256 bonded;
Coupons coupons;
}
}
contract Candidate {
enum Vote {
UNDECIDED,
APPROVE,
REJECT
}
struct State {
uint256 start;
uint256 period;
uint256 approve;
uint256 reject;
mapping(address => Vote) votes;
bool initialized;
}
}
contract Era {
enum Status {
EXPANSION,
CONTRACTION
}
struct State {
Status status;
uint256 start;
}
}
contract Storage {
struct Provider {
IDollar dollar;
IOracle oracle;
address pool;
}
struct Balance {
uint256 supply;
uint256 bonded;
uint256 staged;
uint256 redeemable;
uint256 debt;
uint256 coupons;
}
struct State {
Epoch.Global epoch;
Balance balance;
Provider provider;
mapping(address => Account.State) accounts;
mapping(uint256 => Epoch.State) epochs;
mapping(address => Candidate.State) candidates;
}
struct State16 {
mapping(address => mapping(uint256 => uint256)) couponUnderlyingByAccount;
uint256 couponUnderlying;
}
struct State18 {
Era.State era;
}
struct State25 {
uint256 poolTotalRewarded;
uint256 poolDollarWithdrawable;
mapping(address => bool) poolWithdrawn;
address owner;
}
}
contract State {
Storage.State _state;
// EIP-16
Storage.State16 _state16;
// EIP-18
Storage.State18 _state18;
// EIP-25
Storage.State25 _state25;
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract IDAO {
function epoch() external view returns (uint256);
event Advance(uint256 indexed epoch, uint256 block, uint256 timestamp);
event Incentivization(address indexed account, uint256 amount);
event IncentivizationWithStake(address indexed account, uint256 amount);
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
event TokenSplitSnapshot(uint256 totalBonded, uint256 totalStake);
/* Regulator */
event SupplyIncrease(uint256 indexed epoch, uint256 price, uint256 newRedeemable, uint256 lessDebt, uint256 newBonded);
event SupplyDecrease(uint256 indexed epoch, uint256 price, uint256 newDebt);
event SupplyNeutral(uint256 indexed epoch);
/* Stabilizer */
event StabilityReward(uint256 indexed epoch, uint256 rate, uint256 amount);
/* Bonding */
event Deposit(address indexed account, uint256 value);
event Withdraw(address indexed account, uint256 value);
event Bond(address indexed account, uint256 start, uint256 value, uint256 valueUnderlying);
event Unbond(address indexed account, uint256 start, uint256 value, uint256 valueUnderlying);
/* Market */
event CouponExpiration(uint256 indexed epoch, uint256 couponsExpired, uint256 lessRedeemable, uint256 lessDebt, uint256 newBonded);
event CouponPurchase(address indexed account, uint256 indexed epoch, uint256 dollarAmount, uint256 couponAmount);
event CouponRedemption(address indexed account, uint256 indexed epoch, uint256 amount, uint256 couponAmount);
event CouponTransfer(address indexed from, address indexed to, uint256 indexed epoch, uint256 value);
event CouponApproval(address indexed owner, address indexed spender, uint256 value);
/* Governance */
event Proposal(address indexed candidate, address indexed account, uint256 indexed start, uint256 period);
event Vote(address indexed account, address indexed candidate, Candidate.Vote vote, uint256 bonded);
event Commit(address indexed account, address indexed candidate);
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract IPool {
/*
* Emergency Functions
*/
function emergencyWithdraw(address token, uint256 value) external;
function emergencyPause() external;
/*
* Getters
*/
function totalBonded() public view returns (uint256);
function totalStaged() public view returns (uint256);
function totalClaimable() public view returns (uint256);
function totalRewarded() public view returns (uint256);
function totalPhantom() public view returns (uint256);
function univ2() public view returns (IERC20);
/**
* Account
*/
function balanceOfStaged(address account) public view returns (uint256);
function balanceOfClaimable(address account) public view returns (uint256);
function balanceOfBonded(address account) public view returns (uint256);
function balanceOfPhantom(address account) public view returns (uint256);
function balanceOfRewarded(address account) public view returns (uint256);
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
library Constants {
/* Chain */
uint256 private constant CHAIN_ID = 1; // Mainnet
/* Oracle */
address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
uint256 private constant ORACLE_RESERVE_MINIMUM = 1e10; // 10,000 USDC
/* Bonding */
uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 ESD -> 100M ESDS
/* Epoch */
struct EpochStrategy {
uint256 offset;
uint256 start;
uint256 period;
}
/* DAO */
uint256 private constant ADVANCE_INCENTIVE = 2500e18; // 2500 ESD
/* Pool */
uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 5; // 5 epochs fluid
/* Deployed */
address private constant DAO_ADDRESS = address(0x443D2f2755DB5942601fa062Cc248aAA153313D3);
address private constant DOLLAR_ADDRESS = address(0x36F3FD68E7325a35EB768F1AedaAe9EA0689d723);
address private constant PAIR_ADDRESS = address(0x88ff79eB2Bc5850F27315415da8685282C7610F9);
address private constant TREASURY_ADDRESS = address(0x460661bd4A5364A3ABCc9cfc4a8cE7038d05Ea22);
address private constant POOL_ADDRESS = address(0x4082D11E506e3250009A991061ACd2176077C88f);
address private constant ORACLE_ADDRESS = address(0xea9f8bb8B5e8BA3D38628f0E18Ee82300eddBa0E);
address private constant V2_MIGRATOR_ADDRESS = address(0xC61D12896421613b30D56F85c093CdDa43Ab2CE7);
address private constant V2_DAO_ADDRESS = address(0x1bba92F379375387bf8F927058da14D47464cB7A);
/**
* Getters
*/
function getUsdcAddress() internal pure returns (address) {
return USDC;
}
function getOracleReserveMinimum() internal pure returns (uint256) {
return ORACLE_RESERVE_MINIMUM;
}
function getInitialStakeMultiple() internal pure returns (uint256) {
return INITIAL_STAKE_MULTIPLE;
}
function getAdvanceIncentive() internal pure returns (uint256) {
return ADVANCE_INCENTIVE;
}
function getPoolExitLockupEpochs() internal pure returns (uint256) {
return POOL_EXIT_LOCKUP_EPOCHS;
}
function getChainId() internal pure returns (uint256) {
return CHAIN_ID;
}
function getDaoAddress() internal pure returns (address) {
return DAO_ADDRESS;
}
function getDollarAddress() internal pure returns (address) {
return DOLLAR_ADDRESS;
}
function getPairAddress() internal pure returns (address) {
return PAIR_ADDRESS;
}
function getTreasuryAddress() internal pure returns (address) {
return TREASURY_ADDRESS;
}
function getPoolAddress() internal pure returns (address) {
return POOL_ADDRESS;
}
function getOracleAddress() internal pure returns (address) {
return ORACLE_ADDRESS;
}
function getV2MigratorAddress() internal pure returns (address) {
return V2_MIGRATOR_ADDRESS;
}
function getV2DaoAddress() internal pure returns (address) {
return V2_DAO_ADDRESS;
}
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract Getters is State {
using SafeMath for uint256;
using Decimal for Decimal.D256;
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* ERC20 Interface
*/
function name() public view returns (string memory) {
return "Empty Set Dollar Stake";
}
function symbol() public view returns (string memory) {
return "ESDS";
}
function decimals() public view returns (uint8) {
return 18;
}
function balanceOf(address account) public view returns (uint256) {
return _state.accounts[account].balance;
}
function totalSupply() public view returns (uint256) {
return _state.balance.supply;
}
function allowance(address owner, address spender) external view returns (uint256) {
return 0;
}
/**
* Global
*/
function dollar() public view returns (IDollar) {
return IDollar(Constants.getDollarAddress());
}
function oracle() public view returns (IOracle) {
return IOracle(Constants.getOracleAddress());
}
function pool() public view returns (IPool) {
return IPool(Constants.getPoolAddress());
}
function univ2() public view returns (IERC20) {
return IERC20(Constants.getPairAddress());
}
function v2Migrator() public view returns (address) {
return Constants.getV2MigratorAddress();
}
function owner() public view returns (address) {
return _state25.owner;
}
function totalBonded() public view returns (uint256) {
return _state.balance.bonded;
}
function totalStaged() public view returns (uint256) {
return _state.balance.staged;
}
function totalCouponUnderlying() public view returns (uint256) {
return _state16.couponUnderlying;
}
function totalNet() public view returns (uint256) {
return dollar().totalSupply().sub(totalDebt());
}
/**
* Account
*/
function balanceOfStaged(address account) public view returns (uint256) {
return _state.accounts[account].staged;
}
function balanceOfBonded(address account) public view returns (uint256) {
uint256 totalSupply = totalSupply();
if (totalSupply == 0) {
return 0;
}
return totalBonded().mul(balanceOf(account)).div(totalSupply);
}
function balanceOfCouponUnderlying(address account, uint256 epoch) public view returns (uint256) {
return _state16.couponUnderlyingByAccount[account][epoch];
}
function statusOf(address account) public view returns (Account.Status) {
if (_state.accounts[account].lockedUntil > epoch()) {
return Account.Status.Locked;
}
return epoch() >= _state.accounts[account].fluidUntil ? Account.Status.Frozen : Account.Status.Fluid;
}
function fluidUntil(address account) public view returns (uint256) {
return _state.accounts[account].fluidUntil;
}
function lockedUntil(address account) public view returns (uint256) {
return _state.accounts[account].lockedUntil;
}
function allowanceCoupons(address owner, address spender) public view returns (uint256) {
return _state.accounts[owner].couponAllowances[spender];
}
/**
* Epoch
*/
function epoch() public view returns (uint256) {
return _state.epoch.current;
}
function epochTime() public view returns (uint256) {
return epoch();
}
function epochTimeWithStrategy(Constants.EpochStrategy memory strategy) private view returns (uint256) {
return blockTimestamp()
.sub(strategy.start)
.div(strategy.period)
.add(strategy.offset);
}
// Overridable for testing
function blockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
function couponsExpiration(uint256 epoch) public view returns (uint256) {
return _state.epochs[epoch].coupons.expiration;
}
function expiringCoupons(uint256 epoch) public view returns (uint256) {
return _state.epochs[epoch].coupons.expiring.length;
}
function expiringCouponsAtIndex(uint256 epoch, uint256 i) public view returns (uint256) {
return _state.epochs[epoch].coupons.expiring[i];
}
function totalBondedAt(uint256 epoch) public view returns (uint256) {
return _state.epochs[epoch].bonded;
}
/**
* Governance
*/
function recordedVote(address account, address candidate) public view returns (Candidate.Vote) {
return _state.candidates[candidate].votes[account];
}
function startFor(address candidate) public view returns (uint256) {
return _state.candidates[candidate].start;
}
function periodFor(address candidate) public view returns (uint256) {
return _state.candidates[candidate].period;
}
function approveFor(address candidate) public view returns (uint256) {
return _state.candidates[candidate].approve;
}
function rejectFor(address candidate) public view returns (uint256) {
return _state.candidates[candidate].reject;
}
function votesFor(address candidate) public view returns (uint256) {
return approveFor(candidate).add(rejectFor(candidate));
}
function isNominated(address candidate) public view returns (bool) {
return _state.candidates[candidate].start > 0;
}
function isInitialized(address candidate) public view returns (bool) {
return _state.candidates[candidate].initialized;
}
function implementation() public view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* Pool Migration
*/
function poolTotalRewarded() public view returns (uint256) {
return _state25.poolTotalRewarded;
}
function poolHasWithdrawn(address account) public view returns (bool) {
return _state25.poolWithdrawn[account];
}
function poolWithdrawable(address account) public view returns (uint256, uint256) {
if (poolHasWithdrawn(account)) {
return (0, 0);
}
uint256 univ2Amount = pool().balanceOfBonded(account).add(pool().balanceOfStaged(account));
uint256 dollarAmount = pool().balanceOfClaimable(account).add(poolBalanceOfRewarded(account));
return (univ2Amount, dollarAmount);
}
function poolBalanceOfRewarded(address account) internal view returns (uint256) {
uint256 totalBonded = pool().totalBonded();
if (totalBonded == 0) {
return 0;
}
uint256 totalRewardedWithPhantom = poolTotalRewarded().add(pool().totalPhantom());
uint256 balanceOfRewardedWithPhantom = totalRewardedWithPhantom
.mul(pool().balanceOfBonded(account))
.div(totalBonded);
uint256 balanceOfPhantom = pool().balanceOfPhantom(account);
if (balanceOfRewardedWithPhantom > balanceOfPhantom) {
return balanceOfRewardedWithPhantom.sub(balanceOfPhantom);
}
return 0;
}
function poolDollarWithdrawable() public view returns (uint256) {
return _state25.poolDollarWithdrawable;
}
/*
* DEPRECATED
*/
function totalCoupons() public view returns (uint256) {
return 0;
}
function balanceOfCoupons(address account, uint256 epoch) public view returns (uint256) {
return 0;
}
function outstandingCoupons(uint256 epoch) public view returns (uint256) {
return 0;
}
function bootstrappingAt(uint256 epoch) public view returns (bool) {
return false;
}
function eraStatus() public view returns (Era.Status) {
return Era.Status.CONTRACTION;
}
function eraStart() public view returns (uint256) {
return 0;
}
function couponPremium(uint256 amount) public view returns (uint256) {
return 0;
}
function totalDebt() public view returns (uint256) {
return 0;
}
function totalRedeemable() public view returns (uint256) {
return 0;
}
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract Setters is State, Getters {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* ERC20 Interface
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
return false;
}
function approve(address spender, uint256 amount) external returns (bool) {
return false;
}
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
return false;
}
/**
* Account
*/
function decrementBalanceOf(address account, uint256 amount, string memory reason) internal {
_state.accounts[account].balance = _state.accounts[account].balance.sub(amount, reason);
_state.balance.supply = _state.balance.supply.sub(amount, reason);
emit Transfer(account, address(0), amount);
}
function incrementBalanceOf(address account, uint256 amount) internal {
_state.accounts[account].balance = _state.accounts[account].balance.add(amount);
_state.balance.supply = _state.balance.supply.add(amount);
emit Transfer(address(0), account, amount);
}
function decrementBalanceOfStaged(address account, uint256 amount, string memory reason) internal {
_state.accounts[account].staged = _state.accounts[account].staged.sub(amount, reason);
_state.balance.staged = _state.balance.staged.sub(amount, reason);
}
function incrementBalanceOfCouponUnderlying(address account, uint256 epoch, uint256 amount) internal {
_state16.couponUnderlyingByAccount[account][epoch] = _state16.couponUnderlyingByAccount[account][epoch].add(amount);
_state16.couponUnderlying = _state16.couponUnderlying.add(amount);
}
function decrementBalanceOfCouponUnderlying(address account, uint256 epoch, uint256 amount, string memory reason) internal {
_state16.couponUnderlyingByAccount[account][epoch] = _state16.couponUnderlyingByAccount[account][epoch].sub(amount, reason);
_state16.couponUnderlying = _state16.couponUnderlying.sub(amount, reason);
}
function updateAllowanceCoupons(address owner, address spender, uint256 amount) internal {
_state.accounts[owner].couponAllowances[spender] = amount;
}
function decrementAllowanceCoupons(address owner, address spender, uint256 amount, string memory reason) internal {
_state.accounts[owner].couponAllowances[spender] =
_state.accounts[owner].couponAllowances[spender].sub(amount, reason);
}
/**
* Governance
*/
function initialized(address candidate) internal {
_state.candidates[candidate].initialized = true;
}
/**
* Pool Migration - EIP25
*/
function snapshotPoolTotalRewarded(uint256 totalRewarded) internal {
_state25.poolTotalRewarded = totalRewarded;
}
function snapshotPoolTotalDollar(uint256 total) internal {
_state25.poolDollarWithdrawable = total;
}
function decrementPoolDollarWithdrawable(uint256 amount, string memory reason) internal {
_state25.poolDollarWithdrawable = _state25.poolDollarWithdrawable.sub(amount, reason);
}
function poolMarkWithdrawn(address account) internal {
_state25.poolWithdrawn[account] = true;
}
function setOwner(address newOwner) internal {
_state25.owner = newOwner;
}
}
/*
Copyright 2019 dYdX Trading 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.
*/
/**
* @title Require
* @author dYdX
*
* Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
*/
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract Permission is Setters {
bytes32 private constant FILE = "Permission";
modifier initializer() {
Require.that(
!isInitialized(implementation()),
FILE,
"Already initialized"
);
initialized(implementation());
_;
}
modifier onlyV2Migrator() {
Require.that(
msg.sender == v2Migrator(), // v2 Migrator
FILE,
"Not migrator"
);
_;
}
modifier onlyOwner() {
Require.that(
msg.sender == owner(), // v2 DAO
FILE,
"Not owner"
);
_;
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/*
Copyright 2018-2019 zOS Global Limited
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
/**
* Based off of, and designed to interface with, openzeppelin/upgrades package
*/
contract Upgradeable is State {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
function initialize() public;
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) internal {
setImplementation(newImplementation);
(bool success, bytes memory reason) = newImplementation.delegatecall(abi.encodeWithSignature("initialize()"));
require(success, string(reason));
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function setImplementation(address newImplementation) private {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.
*/
contract Implementation is IDAO, Setters, Permission, Upgradeable {
using SafeMath for uint256;
function initialize() initializer public {
// Reward committer
incentivize(msg.sender, Constants.getAdvanceIncentive());
// Dev rewards
incentivizeWithStake(address(0xdaeD3f8E267CF2e5480A379d75BfABad58ab2144), 3000000e18);
/*
EIP25 Pool Migration:
1. emergencyPause() the pool
2. snapshot poolBalance = pool().totalRewarded()
3. emergencyWithdraw(dollar(), poolBalance)
4. emergencyWithdraw(univ2(), uniV2Balance) univ2Balance = pool.totalBonded + pool.totalStaged
5. Set the owner to v2 DAO
*/
// Emergency Pause the Pool
pool().emergencyPause();
// Snapshot pool total rewarded
snapshotPoolTotalRewarded(pool().totalRewarded());
uint256 poolDollar = dollar().balanceOf(address(pool()));
snapshotPoolTotalDollar(poolDollar);
// Withdraw dollar and univ2
pool().emergencyWithdraw(address(dollar()), poolDollar);
pool().emergencyWithdraw(address(pool().univ2()), pool().univ2().balanceOf(address(pool())));
// set owner
setOwner(Constants.getV2DaoAddress()); // V2 DAO
}
/*
* Continuous Dollar Migration
*/
function burn(address account, uint256 amount) external onlyV2Migrator {
decrementBalanceOf(account, amount, "V1_DAO: insufficient staked balance");
}
/**
* Pool Withdraw
*/
function poolWithdraw() external {
require(!poolHasWithdrawn(msg.sender), "Pool Withdraw: already withdrawn");
(uint256 univ2Amount, uint256 dollarAmount) = poolWithdrawable(msg.sender);
if (univ2Amount > 0) {
// Transfer univ2
pool().univ2().transfer(msg.sender, univ2Amount);
}
if (dollarAmount > 0) {
// Transfer dollar
dollar().transfer(msg.sender, dollarAmount);
decrementPoolDollarWithdrawable(dollarAmount, "Pool Withdraw: insufficient Dollar");
}
poolMarkWithdrawn(msg.sender);
}
function incentivize(address account, uint256 amount) private {
dollar().mint(account, amount);
emit Incentivization(account, amount);
}
function incentivizeWithStake(address account, uint256 amount) private {
incrementBalanceOf(account, amount);
emit IncentivizationWithStake(account, amount);
}
/*
* Admin
*/
function commit(address candidate) external onlyOwner {
upgradeTo(candidate);
emit Commit(msg.sender, candidate);
}
function changeOwner(address newOwner) external onlyOwner {
address prevOwner = owner();
setOwner(newOwner);
emit OwnerChanged(prevOwner, newOwner);
}
/*
* Bonding Functions
*/
function withdraw(uint256 value) external {
dollar().transfer(msg.sender, value);
decrementBalanceOfStaged(msg.sender, value, "Bonding: insufficient staged balance");
emit Withdraw(msg.sender, value);
}
/*
* Market Functions
*/
// @notice: logic overview
// Redeem `amount` of underlying at the given `couponEpoch`
// Reverts if balance of underlying at `couponEpoch` is less than `amount`
function redeemCoupons(uint256 couponEpoch, uint256 amount) external {
require(epoch().sub(couponEpoch) >= 2, "Market: Too early to redeem");
require(amount != 0, "Market: Amount too low");
decrementBalanceOfCouponUnderlying(msg.sender, couponEpoch, amount, "Market: Insufficient coupon underlying balance");
dollar().mint(msg.sender, amount);
emit CouponRedemption(msg.sender, couponEpoch, amount, 0);
}
function approveCoupons(address spender, uint256 amount) external {
require(spender != address(0), "Market: Coupon approve to the zero address");
updateAllowanceCoupons(msg.sender, spender, amount);
emit CouponApproval(msg.sender, spender, amount);
}
function transferCoupons(address sender, address recipient, uint256 epoch, uint256 amount) external {
require(sender != address(0), "Market: Coupon transfer from the zero address");
require(recipient != address(0), "Market: Coupon transfer to the zero address");
decrementBalanceOfCouponUnderlying(sender, epoch, amount, "Market: Insufficient coupon underlying balance");
incrementBalanceOfCouponUnderlying(recipient, epoch, amount);
if (msg.sender != sender && allowanceCoupons(sender, msg.sender) != uint256(-1)) {
decrementAllowanceCoupons(sender, msg.sender, amount, "Market: Insufficient coupon approval");
}
emit CouponTransfer(sender, recipient, epoch, amount);
}
}
| Continuous Dollar Migration/ | function burn(address account, uint256 amount) external onlyV2Migrator {
decrementBalanceOf(account, amount, "V1_DAO: insufficient staked balance");
}
| 2,019,308 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ConfigurableOperational
* @notice A configurable with modifiers for operational mode state validation
*/
contract ConfigurableOperational is Configurable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyOperationalModeNormal() {
require(configuration.isOperationalModeNormal(), "Operational mode is not normal [ConfigurableOperational.sol:22]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentTypesLib
* @dev Data types centered around payment
*/
library PaymentTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum PaymentPartyRole {Sender, Recipient}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct PaymentSenderParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
string data;
}
struct PaymentRecipientParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.TotalOriginFigures fees;
}
struct Operator {
uint256 id;
string data;
}
struct Payment {
int256 amount;
MonetaryTypesLib.Currency currency;
PaymentSenderParty sender;
PaymentRecipientParty recipient;
// Positive transfer is always in direction from sender to recipient
NahmiiTypesLib.SingleTotalInt256 transfers;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
Operator operator;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function PAYMENT_KIND()
public
pure
returns (string memory)
{
return "payment";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHasher
* @notice Contract that hashes types related to payment
*/
contract PaymentHasher is Ownable {
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function hashPaymentAsWallet(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 amountCurrencyHash = hashPaymentAmountCurrency(payment);
bytes32 senderHash = hashPaymentSenderPartyAsWallet(payment.sender);
bytes32 recipientHash = hashAddress(payment.recipient.wallet);
return keccak256(abi.encodePacked(amountCurrencyHash, senderHash, recipientHash));
}
function hashPaymentAsOperator(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 walletSignatureHash = hashSignature(payment.seals.wallet.signature);
bytes32 senderHash = hashPaymentSenderPartyAsOperator(payment.sender);
bytes32 recipientHash = hashPaymentRecipientPartyAsOperator(payment.recipient);
bytes32 transfersHash = hashSingleTotalInt256(payment.transfers);
bytes32 operatorHash = hashString(payment.operator.data);
return keccak256(abi.encodePacked(
walletSignatureHash, senderHash, recipientHash, transfersHash, operatorHash
));
}
function hashPaymentAmountCurrency(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
payment.amount,
payment.currency.ct,
payment.currency.id
));
}
function hashPaymentSenderPartyAsWallet(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
paymentSenderParty.wallet,
paymentSenderParty.data
));
}
function hashPaymentSenderPartyAsOperator(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentSenderParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentSenderParty.balances);
bytes32 singleFeeHash = hashFigure(paymentSenderParty.fees.single);
bytes32 totalFeesHash = hashOriginFigures(paymentSenderParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, singleFeeHash, totalFeesHash
));
}
function hashPaymentRecipientPartyAsOperator(
PaymentTypesLib.PaymentRecipientParty memory paymentRecipientParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentRecipientParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentRecipientParty.balances);
bytes32 totalFeesHash = hashOriginFigures(paymentRecipientParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, totalFeesHash
));
}
function hashCurrentPreviousInt256(
NahmiiTypesLib.CurrentPreviousInt256 memory currentPreviousInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
currentPreviousInt256.current,
currentPreviousInt256.previous
));
}
function hashSingleTotalInt256(
NahmiiTypesLib.SingleTotalInt256 memory singleTotalInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
singleTotalInt256.single,
singleTotalInt256.total
));
}
function hashFigure(MonetaryTypesLib.Figure memory figure)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
figure.amount,
figure.currency.ct,
figure.currency.id
));
}
function hashOriginFigures(NahmiiTypesLib.OriginFigure[] memory originFigures)
public
pure
returns (bytes32)
{
bytes32 hash;
for (uint256 i = 0; i < originFigures.length; i++) {
hash = keccak256(abi.encodePacked(
hash,
originFigures[i].originId,
originFigures[i].figure.amount,
originFigures[i].figure.currency.ct,
originFigures[i].figure.currency.id
)
);
}
return hash;
}
function hashUint256(uint256 _uint256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_uint256));
}
function hashString(string memory _string)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
function hashAddress(address _address)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_address));
}
function hashSignature(NahmiiTypesLib.Signature memory signature)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
signature.v,
signature.r,
signature.s
));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHashable
* @notice An ownable that has a payment hasher property
*/
contract PaymentHashable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
PaymentHasher public paymentHasher;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetPaymentHasherEvent(PaymentHasher oldPaymentHasher, PaymentHasher newPaymentHasher);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the payment hasher contract
/// @param newPaymentHasher The (address of) PaymentHasher contract instance
function setPaymentHasher(PaymentHasher newPaymentHasher)
public
onlyDeployer
notNullAddress(address(newPaymentHasher))
notSameAddresses(address(newPaymentHasher), address(paymentHasher))
{
// Set new payment hasher
PaymentHasher oldPaymentHasher = paymentHasher;
paymentHasher = newPaymentHasher;
// Emit event
emit SetPaymentHasherEvent(oldPaymentHasher, newPaymentHasher);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier paymentHasherInitialized() {
require(address(paymentHasher) != address(0), "Payment hasher not initialized [PaymentHashable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManager
* @notice A contract to control who can execute some specific actions
*/
contract SignerManager is Ownable {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => uint256) public signerIndicesMap; // 1 based internally
address[] public signers;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterSignerEvent(address signer);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
registerSigner(deployer);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Gauge whether an address is registered signer
/// @param _address The concerned address
/// @return true if address is registered signer, else false
function isSigner(address _address)
public
view
returns (bool)
{
return 0 < signerIndicesMap[_address];
}
/// @notice Get the count of registered signers
/// @return The count of registered signers
function signersCount()
public
view
returns (uint256)
{
return signers.length;
}
/// @notice Get the 0 based index of the given address in the list of signers
/// @param _address The concerned address
/// @return The index of the signer address
function signerIndex(address _address)
public
view
returns (uint256)
{
require(isSigner(_address), "Address not signer [SignerManager.sol:71]");
return signerIndicesMap[_address] - 1;
}
/// @notice Registers a signer
/// @param newSigner The address of the signer to register
function registerSigner(address newSigner)
public
onlyOperator
notNullOrThisAddress(newSigner)
{
if (0 == signerIndicesMap[newSigner]) {
// Set new operator
signers.push(newSigner);
signerIndicesMap[newSigner] = signers.length;
// Emit event
emit RegisterSignerEvent(newSigner);
}
}
/// @notice Get the subset of registered signers in the given 0 based index range
/// @param low The lower inclusive index
/// @param up The upper inclusive index
/// @return The subset of registered signers
function signersByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < signers.length, "No signers found [SignerManager.sol:101]");
require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]");
up = up.clampMax(signers.length - 1);
address[] memory _signers = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_signers[i - low] = signers[i];
return _signers;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManageable
* @notice A contract to interface ACL
*/
contract SignerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SignerManager public signerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the signer manager of this contract
/// @param newSignerManager The address of the new signer
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
//set new signer
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
// Emit event
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
/// @notice Prefix input hash and do ecrecover on prefixed hash
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return The address recovered
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
/// @notice Gauge whether a signature of a hash has been signed by a registered signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return true if the recovered signer is one of the registered signers, else false
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
/// @notice Gauge whether a signature of a hash has been signed by the claimed signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @param signer The claimed signer
/// @return true if the recovered signer equals the input signer, else false
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validator
* @notice An ownable that validates valuable types (e.g. payment)
*/
contract Validator is Ownable, SignerManageable, Configurable, PaymentHashable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer, address signerManager) Ownable(deployer) SignerManageable(signerManager) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isGenuineOperatorSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature)
public
view
returns (bool)
{
return isSignedByRegisteredSigner(hash, signature.v, signature.r, signature.s);
}
function isGenuineWalletSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature, address wallet)
public
pure
returns (bool)
{
return isSignedBy(hash, signature.v, signature.r, signature.s, wallet);
}
function isGenuinePaymentWalletHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsWallet(payment) == payment.seals.wallet.hash;
}
function isGenuinePaymentOperatorHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsOperator(payment) == payment.seals.operator.hash;
}
function isGenuinePaymentWalletSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletHash(payment)
&& isGenuineWalletSignature(payment.seals.wallet.hash, payment.seals.wallet.signature, payment.sender.wallet);
}
function isGenuinePaymentOperatorSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentOperatorHash(payment)
&& isGenuineOperatorSignature(payment.seals.operator.hash, payment.seals.operator.signature);
}
function isGenuinePaymentSeals(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletSeal(payment) && isGenuinePaymentOperatorSeal(payment);
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentFeeOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
int256 feePartsPer = int256(ConstantsLib.PARTS_PER());
int256 feeAmount = payment.amount
.mul(
configuration.currencyPaymentFee(
payment.blockNumber, payment.currency.ct, payment.currency.id, payment.amount
)
).div(feePartsPer);
if (1 > feeAmount)
feeAmount = 1;
return (payment.sender.fees.single.amount == feeAmount);
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentFeeOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
(address feeCurrencyCt, uint256 feeCurrencyId) = configuration.feeCurrency(
payment.blockNumber, payment.currency.ct, payment.currency.id
);
return feeCurrencyCt == payment.sender.fees.single.currency.ct
&& feeCurrencyId == payment.sender.fees.single.currency.id;
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentSenderOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet))
&& (payment.sender.balances.current == payment.sender.balances.previous.sub(payment.transfers.single).sub(payment.sender.fees.single.amount));
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentRecipientOfFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (payment.recipient.balances.current == payment.recipient.balances.previous.add(payment.transfers.single));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentSenderOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentRecipientOfNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet);
}
function isSuccessivePaymentsPartyNonces(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole
)
public
pure
returns (bool)
{
uint256 firstNonce = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.nonce : firstPayment.recipient.nonce);
uint256 lastNonce = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.nonce : lastPayment.recipient.nonce);
return lastNonce == firstNonce.add(1);
}
function isGenuineSuccessivePaymentsBalances(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole,
int256 delta
)
public
pure
returns (bool)
{
NahmiiTypesLib.CurrentPreviousInt256 memory firstCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.balances : firstPayment.recipient.balances);
NahmiiTypesLib.CurrentPreviousInt256 memory lastCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.balances : lastPayment.recipient.balances);
return lastCurrentPreviousBalances.previous == firstCurrentPreviousBalances.current.add(delta);
}
function isGenuineSuccessivePaymentsTotalFees(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.Payment memory lastPayment
)
public
pure
returns (bool)
{
MonetaryTypesLib.Figure memory firstTotalFee = getProtocolFigureByCurrency(firstPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
MonetaryTypesLib.Figure memory lastTotalFee = getProtocolFigureByCurrency(lastPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
return lastTotalFee.amount == firstTotalFee.amount.add(lastPayment.sender.fees.single.amount);
}
function isPaymentParty(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet || wallet == payment.recipient.wallet;
}
function isPaymentSender(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet;
}
function isPaymentRecipient(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.recipient.wallet;
}
function isPaymentCurrency(PaymentTypesLib.Payment memory payment, MonetaryTypesLib.Currency memory currency)
public
pure
returns (bool)
{
return currency.ct == payment.currency.ct && currency.id == payment.currency.id;
}
function isPaymentCurrencyNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return payment.currency.ct != payment.sender.fees.single.currency.ct
|| payment.currency.id != payment.sender.fees.single.currency.id;
}
//
// Private unctions
// -----------------------------------------------------------------------------------------------------------------
function getProtocolFigureByCurrency(NahmiiTypesLib.OriginFigure[] memory originFigures, MonetaryTypesLib.Currency memory currency)
private
pure
returns (MonetaryTypesLib.Figure memory) {
for (uint256 i = 0; i < originFigures.length; i++)
if (originFigures[i].figure.currency.ct == currency.ct && originFigures[i].figure.currency.id == currency.id
&& originFigures[i].originId == 0)
return originFigures[i].figure;
return MonetaryTypesLib.Figure(0, currency);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TradeTypesLib
* @dev Data types centered around trade
*/
library TradeTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum CurrencyRole {Intended, Conjugate}
enum LiquidityRole {Maker, Taker}
enum Intention {Buy, Sell}
enum TradePartyRole {Buyer, Seller}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OrderPlacement {
Intention intention;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct Order {
uint256 nonce;
address wallet;
OrderPlacement placement;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
uint256 operatorId;
}
struct TradeOrder {
int256 amount;
NahmiiTypesLib.WalletOperatorHashes hashes;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct TradeParty {
uint256 nonce;
address wallet;
uint256 rollingVolume;
LiquidityRole liquidityRole;
TradeOrder order;
NahmiiTypesLib.IntendedConjugateCurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
}
struct Trade {
uint256 nonce;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
TradeParty buyer;
TradeParty seller;
// Positive intended transfer is always in direction from seller to buyer
// Positive conjugate transfer is always in direction from buyer to seller
NahmiiTypesLib.IntendedConjugateSingleTotalInt256 transfers;
NahmiiTypesLib.Seal seal;
uint256 blockNumber;
uint256 operatorId;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function TRADE_KIND()
public
pure
returns (string memory)
{
return "trade";
}
function ORDER_KIND()
public
pure
returns (string memory)
{
return "order";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validatable
* @notice An ownable that has a validator property
*/
contract Validatable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Validator public validator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetValidatorEvent(Validator oldValidator, Validator newValidator);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the validator contract
/// @param newValidator The (address of) Validator contract instance
function setValidator(Validator newValidator)
public
onlyDeployer
notNullAddress(address(newValidator))
notSameAddresses(address(newValidator), address(validator))
{
//set new validator
Validator oldValidator = validator;
validator = newValidator;
// Emit event
emit SetValidatorEvent(oldValidator, newValidator);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier validatorInitialized() {
require(address(validator) != address(0), "Validator not initialized [Validatable.sol:55]");
_;
}
modifier onlyOperatorSealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentOperatorSeal(payment), "Payment operator seal not genuine [Validatable.sol:60]");
_;
}
modifier onlySealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentSeals(payment), "Payment seals not genuine [Validatable.sol:65]");
_;
}
modifier onlyPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentParty(payment, wallet), "Wallet not payment party [Validatable.sol:70]");
_;
}
modifier onlyPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentSender(payment, wallet), "Wallet not payment sender [Validatable.sol:75]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBond
* @notice Fund that contains crypto incentive for challenging operator fraud.
*/
contract SecurityBond is Ownable, Configurable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public REWARD_ACTION = "reward";
string constant public DEPRIVE_ACTION = "deprive";
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct FractionalReward {
uint256 fraction;
uint256 nonce;
uint256 unlockTime;
}
struct AbsoluteReward {
int256 amount;
uint256 nonce;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance private deposited;
TxHistoryLib.TxHistory private txHistory;
CurrenciesLib.Currencies private inUseCurrencies;
mapping(address => FractionalReward) public fractionalRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => AbsoluteReward))) public absoluteRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => uint256))) public claimNonceByWalletCurrency;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
mapping(address => uint256) public nonceByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RewardFractionalEvent(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds);
event RewardAbsoluteEvent(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds);
event DepriveFractionalEvent(address wallet);
event DepriveAbsoluteEvent(address wallet, address currencyCt, uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address from, Beneficiary beneficiary, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Servable() public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balance
deposited.add(amount, address(0), 0);
txHistory.addDeposit(amount, address(0), 0);
// Add currency to in-use list
inUseCurrencies.add(address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:145]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [SecurityBond.sol:154]");
// Add to balance
deposited.add(amount, currencyCt, currencyId);
txHistory.addDeposit(amount, currencyCt, currencyId);
// Add currency to in-use list
inUseCurrencies.add(currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the deposited balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function depositedBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId);
}
/// @notice Get the fractional amount deposited balance of the given currency
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
/// @param fraction The fraction of sums that the wallet is rewarded
/// @return The fractional amount of deposited balance
function depositedFractionalBalance(address currencyCt, uint256 currencyId, uint256 fraction)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fraction))
.div(ConstantsLib.PARTS_PER());
}
/// @notice Get the staged balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded
/// @return The number of currencies
function inUseCurrenciesCount()
public
view
returns (uint256)
{
return inUseCurrencies.count();
}
/// @notice Get the currencies recorded with indices in the given range
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range
function inUseCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return inUseCurrencies.getByIndices(low, up);
}
/// @notice Reward the given wallet the given fraction of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param fraction The fraction of sums that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardFractional(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = fraction.clampMax(uint256(ConstantsLib.PARTS_PER()));
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardFractionalEvent(wallet, fraction, unlockTimeoutInSeconds);
}
/// @notice Reward the given wallet the given amount of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param amount The amount that the wallet is rewarded
/// @param currencyCt The contract address of the currency that the wallet is rewarded
/// @param currencyId The ID of the currency that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardAbsolute(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = amount;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardAbsoluteEvent(wallet, amount, currencyCt, currencyId, unlockTimeoutInSeconds);
}
/// @notice Deprive the given wallet of any fractional reward it has been granted
/// @param wallet The concerned wallet
function depriveFractional(address wallet)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = 0;
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = 0;
// Emit event
emit DepriveFractionalEvent(wallet);
}
/// @notice Deprive the given wallet of any absolute reward it has been granted in the given currency
/// @param wallet The concerned wallet
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
function depriveAbsolute(address wallet, address currencyCt, uint256 currencyId)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = 0;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = 0;
// Emit event
emit DepriveAbsoluteEvent(wallet, currencyCt, currencyId);
}
/// @notice Claim reward and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(msg.sender, balanceType);
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [SecurityBond.sol:350]");
beneficiary.receiveTokensTo(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, beneficiary, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim reward and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Add to staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:386]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [SecurityBond.sol:405]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Combine claim nonce from rewards
uint256 claimNonce = fractionalRewardByWallet[wallet].nonce.clampMin(
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce
);
// Require that new claim nonce is strictly greater than current stored one
require(
claimNonce > claimNonceByWalletCurrency[wallet][currencyCt][currencyId],
"Claim nonce not strictly greater than previously claimed nonce [SecurityBond.sol:425]"
);
// Combine claim amount from rewards
int256 claimAmount = _fractionalRewardAmountByWalletCurrency(wallet, currencyCt, currencyId).add(
_absoluteRewardAmountByWalletCurrency(wallet, currencyCt, currencyId)
).clampMax(
deposited.get(currencyCt, currencyId)
);
// Require that claim amount is strictly positive, indicating that there is an amount to claim
require(claimAmount.isNonZeroPositiveInt256(), "Claim amount not strictly positive [SecurityBond.sol:438]");
// Update stored claim nonce for wallet and currency
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] = claimNonce;
return claimAmount;
}
function _fractionalRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < fractionalRewardByWallet[wallet].nonce &&
block.timestamp >= fractionalRewardByWallet[wallet].unlockTime
)
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fractionalRewardByWallet[wallet].fraction))
.div(ConstantsLib.PARTS_PER());
else
return 0;
}
function _absoluteRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce &&
block.timestamp >= absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime
)
return absoluteRewardByWallet[wallet][currencyCt][currencyId].amount.clampMax(
deposited.get(currencyCt, currencyId)
);
else
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBondable
* @notice An ownable that has a security bond property
*/
contract SecurityBondable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SecurityBond public securityBond;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSecurityBondEvent(SecurityBond oldSecurityBond, SecurityBond newSecurityBond);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the security bond contract
/// @param newSecurityBond The (address of) SecurityBond contract instance
function setSecurityBond(SecurityBond newSecurityBond)
public
onlyDeployer
notNullAddress(address(newSecurityBond))
notSameAddresses(address(newSecurityBond), address(securityBond))
{
//set new security bond
SecurityBond oldSecurityBond = securityBond;
securityBond = newSecurityBond;
// Emit event
emit SetSecurityBondEvent(oldSecurityBond, newSecurityBond);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier securityBondInitialized() {
require(address(securityBond) != address(0), "Security bond not initialized [SecurityBondable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallenge
* @notice Where fraud challenge results are found
*/
contract FraudChallenge is Ownable, Servable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public ADD_SEIZED_WALLET_ACTION = "add_seized_wallet";
string constant public ADD_DOUBLE_SPENDER_WALLET_ACTION = "add_double_spender_wallet";
string constant public ADD_FRAUDULENT_ORDER_ACTION = "add_fraudulent_order";
string constant public ADD_FRAUDULENT_TRADE_ACTION = "add_fraudulent_trade";
string constant public ADD_FRAUDULENT_PAYMENT_ACTION = "add_fraudulent_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address[] public doubleSpenderWallets;
mapping(address => bool) public doubleSpenderByWallet;
bytes32[] public fraudulentOrderHashes;
mapping(bytes32 => bool) public fraudulentByOrderHash;
bytes32[] public fraudulentTradeHashes;
mapping(bytes32 => bool) public fraudulentByTradeHash;
bytes32[] public fraudulentPaymentHashes;
mapping(bytes32 => bool) public fraudulentByPaymentHash;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AddDoubleSpenderWalletEvent(address wallet);
event AddFraudulentOrderHashEvent(bytes32 hash);
event AddFraudulentTradeHashEvent(bytes32 hash);
event AddFraudulentPaymentHashEvent(bytes32 hash);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the number of wallets tagged as double spenders
/// @return Number of double spender wallets
function doubleSpenderWalletsCount()
public
view
returns (uint256)
{
return doubleSpenderWallets.length;
}
/// @notice Add given wallets to store of double spender wallets if not already present
/// @param wallet The first wallet to add
function addDoubleSpenderWallet(address wallet)
public
onlyEnabledServiceAction(ADD_DOUBLE_SPENDER_WALLET_ACTION) {
if (!doubleSpenderByWallet[wallet]) {
doubleSpenderWallets.push(wallet);
doubleSpenderByWallet[wallet] = true;
emit AddDoubleSpenderWalletEvent(wallet);
}
}
/// @notice Get the number of fraudulent order hashes
function fraudulentOrderHashesCount()
public
view
returns (uint256)
{
return fraudulentOrderHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent order
/// @param hash The hash to be tested
function isFraudulentOrderHash(bytes32 hash)
public
view returns (bool) {
return fraudulentByOrderHash[hash];
}
/// @notice Add given order hash to store of fraudulent order hashes if not already present
function addFraudulentOrderHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_ORDER_ACTION)
{
if (!fraudulentByOrderHash[hash]) {
fraudulentByOrderHash[hash] = true;
fraudulentOrderHashes.push(hash);
emit AddFraudulentOrderHashEvent(hash);
}
}
/// @notice Get the number of fraudulent trade hashes
function fraudulentTradeHashesCount()
public
view
returns (uint256)
{
return fraudulentTradeHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent trade
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent trade, else false
function isFraudulentTradeHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByTradeHash[hash];
}
/// @notice Add given trade hash to store of fraudulent trade hashes if not already present
function addFraudulentTradeHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_TRADE_ACTION)
{
if (!fraudulentByTradeHash[hash]) {
fraudulentByTradeHash[hash] = true;
fraudulentTradeHashes.push(hash);
emit AddFraudulentTradeHashEvent(hash);
}
}
/// @notice Get the number of fraudulent payment hashes
function fraudulentPaymentHashesCount()
public
view
returns (uint256)
{
return fraudulentPaymentHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent payment
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent payment, else null
function isFraudulentPaymentHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByPaymentHash[hash];
}
/// @notice Add given payment hash to store of fraudulent payment hashes if not already present
function addFraudulentPaymentHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_PAYMENT_ACTION)
{
if (!fraudulentByPaymentHash[hash]) {
fraudulentByPaymentHash[hash] = true;
fraudulentPaymentHashes.push(hash);
emit AddFraudulentPaymentHashEvent(hash);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallengable
* @notice An ownable that has a fraud challenge property
*/
contract FraudChallengable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FraudChallenge public fraudChallenge;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetFraudChallengeEvent(FraudChallenge oldFraudChallenge, FraudChallenge newFraudChallenge);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the fraud challenge contract
/// @param newFraudChallenge The (address of) FraudChallenge contract instance
function setFraudChallenge(FraudChallenge newFraudChallenge)
public
onlyDeployer
notNullAddress(address(newFraudChallenge))
notSameAddresses(address(newFraudChallenge), address(fraudChallenge))
{
// Set new fraud challenge
FraudChallenge oldFraudChallenge = fraudChallenge;
fraudChallenge = newFraudChallenge;
// Emit event
emit SetFraudChallengeEvent(oldFraudChallenge, newFraudChallenge);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier fraudChallengeInitialized() {
require(address(fraudChallenge) != address(0), "Fraud challenge not initialized [FraudChallengable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BalanceTrackerLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
function fungibleActiveRecordByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 _blockNumber)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.depositedBalanceType(), currency.ct, currency.id, _blockNumber
);
(int256 settledAmount, uint256 settledBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.settledBalanceType(), currency.ct, currency.id, _blockNumber
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
function fungibleActiveBalanceAmountByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = fungibleActiveRecordByBlockNumber(self, wallet, currency, blockNumber);
return amount;
}
function fungibleActiveDeltaBalanceAmountByBlockNumbers(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 fromBlockNumber, uint256 toBlockNumber)
internal
view
returns (int256)
{
return fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, toBlockNumber) -
fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, fromBlockNumber);
}
// TODO Rename?
function fungibleActiveRecord(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.lastFungibleRecord(
wallet, self.depositedBalanceType(), currency.ct, currency.id
);
(int256 settledAmount, uint256 settledBlockNumber) = self.lastFungibleRecord(
wallet, self.settledBalanceType(), currency.ct, currency.id
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
// TODO Rename?
function fungibleActiveBalanceAmount(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256)
{
return self.get(wallet, self.depositedBalanceType(), currency.ct, currency.id).add(
self.get(wallet, self.settledBalanceType(), currency.ct, currency.id)
);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementDisputeByPayment
* @notice The where payment related disputes of null settlement challenge happens
*/
contract NullSettlementDisputeByPayment is Ownable, Configurable, Validatable, SecurityBondable, WalletLockable,
BalanceTrackable, FraudChallengable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CHALLENGE_BY_PAYMENT_ACTION = "challenge_by_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event ChallengeByPaymentEvent(address wallet, uint256 nonce, PaymentTypesLib.Payment payment,
address challenger);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
/// @notice Set the settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Challenge the settlement by providing payment candidate
/// @dev This challenges the payment sender's side of things
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges
/// @param challenger The address of the challenger
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment, address challenger)
public
onlyEnabledServiceAction(CHALLENGE_BY_PAYMENT_ACTION)
onlySealedPayment(payment)
onlyPaymentSender(payment, wallet)
{
// Require that payment candidate is not labelled fraudulent
require(!fraudChallenge.isFraudulentPaymentHash(payment.seals.operator.hash), "Payment deemed fraudulent [NullSettlementDisputeByPayment.sol:86]");
// Require that proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, payment.currency), "No proposal found [NullSettlementDisputeByPayment.sol:89]");
// Require that proposal has not expired
require(!nullSettlementChallengeState.hasProposalExpired(wallet, payment.currency), "Proposal found expired [NullSettlementDisputeByPayment.sol:92]");
// Require that payment party's nonce is strictly greater than proposal's nonce and its current
// disqualification nonce
require(payment.sender.nonce > nullSettlementChallengeState.proposalNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal nonce [NullSettlementDisputeByPayment.sol:96]");
require(payment.sender.nonce > nullSettlementChallengeState.proposalDisqualificationNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal disqualification nonce [NullSettlementDisputeByPayment.sol:99]");
// Require overrun for this payment to be a valid challenge candidate
require(_overrun(wallet, payment), "No overrun found [NullSettlementDisputeByPayment.sol:104]");
// Reward challenger
_settleRewards(wallet, payment.sender.balances.current, payment.currency, challenger);
// Disqualify proposal, effectively overriding any previous disqualification
nullSettlementChallengeState.disqualifyProposal(
wallet, payment.currency, challenger, payment.blockNumber,
payment.sender.nonce, payment.seals.operator.hash, PaymentTypesLib.PAYMENT_KIND()
);
// Emit event
emit ChallengeByPaymentEvent(
wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), payment, challenger
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _overrun(address wallet, PaymentTypesLib.Payment memory payment)
private
view
returns (bool)
{
// Get the target balance amount from the proposal
int targetBalanceAmount = nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, payment.currency
);
// Get the change in active balance since the start of the challenge
int256 deltaBalanceSinceStart = balanceTracker.fungibleActiveBalanceAmount(
wallet, payment.currency
).sub(
balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency,
nullSettlementChallengeState.proposalReferenceBlockNumber(wallet, payment.currency)
)
);
// Get the cumulative transfer of the payment
int256 cumulativeTransfer = balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency, payment.blockNumber
).sub(payment.sender.balances.current);
return targetBalanceAmount.add(deltaBalanceSinceStart) < cumulativeTransfer;
}
// Lock wallet's balances or reward challenger by stake fraction
function _settleRewards(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
if (nullSettlementChallengeState.proposalWalletInitiated(wallet, currency))
_settleBalanceReward(wallet, walletAmount, currency, challenger);
else
_settleSecurityBondReward(wallet, walletAmount, currency, challenger);
}
function _settleBalanceReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Unlock wallet/currency for existing challenger if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
walletLocker.unlockFungibleByProxy(
wallet,
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Lock wallet for new challenger
walletLocker.lockFungibleByProxy(
wallet, challenger, walletAmount, currency.ct, currency.id, configuration.settlementChallengeTimeout()
);
}
// Settle the two-component reward from security bond.
// The first component is flat figure as obtained from Configuration
// The second component is progressive and calculated as
// min(walletAmount, fraction of SecurityBond's deposited balance)
// both amounts for the given currency
function _settleSecurityBondReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Deprive existing challenger of reward if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
securityBond.depriveAbsolute(
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Reward the flat component
MonetaryTypesLib.Figure memory flatReward = _flatReward();
securityBond.rewardAbsolute(
challenger, flatReward.amount, flatReward.currency.ct, flatReward.currency.id, 0
);
// Reward the progressive component
int256 progressiveRewardAmount = walletAmount.clampMax(
securityBond.depositedFractionalBalance(
currency.ct, currency.id, configuration.operatorSettlementStakeFraction()
)
);
securityBond.rewardAbsolute(
challenger, progressiveRewardAmount, currency.ct, currency.id, 0
);
}
function _flatReward()
private
view
returns (MonetaryTypesLib.Figure memory)
{
(int256 amount, address currencyCt, uint256 currencyId) = configuration.operatorSettlementStake();
return MonetaryTypesLib.Figure(amount, MonetaryTypesLib.Currency(currencyCt, currencyId));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeByPayment
* @notice Where null settlements pertaining to payments are started and disputed
*/
contract NullSettlementChallengeByPayment is Ownable, ConfigurableOperational, BalanceTrackable, WalletLockable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementDisputeByPayment public nullSettlementDisputeByPayment;
NullSettlementChallengeState public nullSettlementChallengeState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementDisputeByPaymentEvent(NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment,
NullSettlementDisputeByPayment newNullSettlementDisputeByPayment);
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event StartChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId);
event StartChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId, address proxy);
event StopChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId);
event StopChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address proxy);
event ChallengeByPaymentEvent(address challengedWallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address challengerWallet);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the settlement dispute contract
/// @param newNullSettlementDisputeByPayment The (address of) NullSettlementDisputeByPayment contract instance
function setNullSettlementDisputeByPayment(NullSettlementDisputeByPayment newNullSettlementDisputeByPayment)
public
onlyDeployer
notNullAddress(address(newNullSettlementDisputeByPayment))
{
NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment = nullSettlementDisputeByPayment;
nullSettlementDisputeByPayment = newNullSettlementDisputeByPayment;
emit SetNullSettlementDisputeByPaymentEvent(oldNullSettlementDisputeByPayment, nullSettlementDisputeByPayment);
}
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Start settlement challenge
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallenge(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Require that wallet is not locked
require(!walletLocker.isLocked(msg.sender), "Wallet found locked [NullSettlementChallengeByPayment.sol:116]");
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(msg.sender, amount, currency, true);
// Emit event
emit StartChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Start settlement challenge for the given wallet
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(wallet, amount, currency, false);
// Emit event
emit StartChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Stop settlement challenge
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallenge(address currencyCt, uint256 currencyId)
public
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(msg.sender, currency, true);
// Emit event
emit StopChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
nullSettlementChallengeState.proposalStageAmount(msg.sender, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Stop settlement challenge
/// @param wallet The concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallengeByProxy(address wallet, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(wallet, currency, false);
// Emit event
emit StopChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
nullSettlementChallengeState.proposalStageAmount(wallet, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has been defined
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has been initiated, else false
function hasProposal(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposal(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalTerminated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalExpired(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge nonce of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge nonce
function proposalNonce(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalNonce(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal block number of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal block number
function proposalReferenceBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalReferenceBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal end time of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal end time
function proposalExpirationTime(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalExpirationTime(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge status of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge status
function proposalStatus(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (SettlementChallengeTypesLib.Status)
{
return nullSettlementChallengeState.proposalStatus(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalStageAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the balance reward of the given wallet's settlement proposal
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The balance reward of the settlement proposal
function proposalWalletInitiated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.proposalWalletInitiated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenger of the settlement disqualification
function proposalDisqualificationChallenger(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (address)
{
return nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The block number of the settlement disqualification
function proposalDisqualificationBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalDisqualificationBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate kind of the settlement disqualification
function proposalDisqualificationCandidateKind(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (string memory)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateKind(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate hash of the settlement disqualification
function proposalDisqualificationCandidateHash(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bytes32)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateHash(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Challenge the settlement by providing payment candidate
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges the null
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment)
public
onlyOperationalModeNormal
{
// Challenge by payment
nullSettlementDisputeByPayment.challengeByPayment(wallet, payment, msg.sender);
// Emit event
emit ChallengeByPaymentEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, payment.currency),
nullSettlementChallengeState.proposalStageAmount(wallet, payment.currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, payment.currency),
payment.currency.ct, payment.currency.id, msg.sender
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _startChallenge(address wallet, int256 stageAmount, MonetaryTypesLib.Currency memory currency,
bool walletInitiated)
private
{
// Require that current block number is beyond the earliest settlement challenge block number
require(
block.number >= configuration.earliestSettlementBlockNumber(),
"Current block number below earliest settlement block number [NullSettlementChallengeByPayment.sol:443]"
);
// Require that there is no ongoing overlapping null settlement challenge
require(
!nullSettlementChallengeState.hasProposal(wallet, currency) ||
nullSettlementChallengeState.hasProposalExpired(wallet, currency),
"Overlapping null settlement challenge proposal found [NullSettlementChallengeByPayment.sol:449]"
);
// Get the last logged active balance amount and block number, properties of overlapping DSC
// and the baseline nonce
(
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) = _externalProperties(
wallet, currency
);
// Initiate proposal, including assurance that there is no overlap with active proposal
// Target balance amount is calculated as current balance - DSC cumulativeTransferAmount - DSC stage amount - NSC stageAmount
nullSettlementChallengeState.initiateProposal(
wallet, nonce, stageAmount,
activeBalanceAmount.sub(
dscCumulativeTransferAmount.add(dscStageAmount).add(stageAmount)
),
currency,
activeBalanceBlockNumber, walletInitiated
);
}
function _stopChallenge(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
private
{
// Require that there is an unterminated driip settlement challenge proposal
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlementChallengeByPayment.sol:481]");
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlementChallengeByPayment.sol:482]");
// Terminate driip settlement challenge proposal
nullSettlementChallengeState.terminateProposal(
wallet, currency, walletTerminated
);
}
function _externalProperties(address wallet, MonetaryTypesLib.Currency memory currency)
private
view
returns (
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) {
(activeBalanceAmount, activeBalanceBlockNumber) = balanceTracker.fungibleActiveRecord(
wallet, currency
);
if (driipSettlementChallengeState.hasProposal(wallet, currency)) {
if (!driipSettlementChallengeState.hasProposalTerminated(wallet, currency)) {
dscCumulativeTransferAmount = driipSettlementChallengeState.proposalCumulativeTransferAmount(wallet, currency);
dscStageAmount = driipSettlementChallengeState.proposalStageAmount(wallet, currency);
}
nonce = driipSettlementChallengeState.proposalNonce(wallet, currency);
}
if (nullSettlementChallengeState.hasProposal(wallet, currency))
nonce = nonce.clampMin(nullSettlementChallengeState.proposalNonce(wallet, currency));
}
} | Gauge whether the proposal for the given wallet and currency has expired wallet The address of the concerned wallet currency The concerned currency return true if proposal has expired, else false 1-based index | function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
| 12,574,755 |
pragma solidity ^0.4.11;
/*
TenX Buyer
========================
Buys TenX tokens from the crowdsale on your behalf.
Author: /u/Cintix
*/
// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20
// Well, almost. PAY tokens throw on transfer failure instead of returning false.
contract ERC20 {
function transfer(address _to, uint _value);
function balanceOf(address _owner) constant returns (uint balance);
}
// Interface to TenX ICO Contract
contract MainSale {
address public multisigVault;
uint public altDeposits;
function createTokens(address recipient) payable;
}
contract TenXBuyer {
// Store the amount of ETH deposited by each account.
mapping (address => uint) public balances;
// Bounty for executing buy.
uint256 public bounty;
// Track whether the contract has bought the tokens yet.
bool public bought_tokens;
// Record the time the contract bought the tokens.
uint public time_bought;
// Hard Cap of TenX Crowdsale
uint hardcap = 200000 ether;
// Ratio of PAY tokens received to ETH contributed (350 + 20% first-day bonus)
uint pay_per_eth = 420;
// The TenX Token Sale address.
MainSale public sale = MainSale(0xd43D09Ec1bC5e57C8F3D0c64020d403b04c7f783);
// TenX PAY Token Contract address.
ERC20 public token = ERC20(0xB97048628DB6B661D4C2aA833e95Dbe1A905B280);
// The developer address.
address developer = 0x4e6A1c57CdBfd97e8efe831f8f4418b1F2A09e6e;
// Withdraws all ETH deposited or PAY purchased by the sender.
function withdraw(){
// If called before the ICO, cancel caller's participation in the sale.
if (!bought_tokens) {
// Store the user's balance prior to withdrawal in a temporary variable.
uint eth_amount = balances[msg.sender];
// Update the user's balance prior to sending ETH to prevent recursive call.
balances[msg.sender] = 0;
// Return the user's funds. Throws on failure to prevent loss of funds.
msg.sender.transfer(eth_amount);
}
// Withdraw the sender's tokens if the contract has already purchased them.
else {
// Store the user's PAY balance in a temporary variable (1 ETHWei -> 420 PAYWei).
uint pay_amount = balances[msg.sender] * pay_per_eth;
// Update the user's balance prior to sending PAY to prevent recursive call.
balances[msg.sender] = 0;
// No fee for withdrawing during the crowdsale.
uint fee = 0;
// Determine whether the crowdsale's hard cap has been reached yet.
bool cap_reached = (sale.multisigVault().balance + sale.altDeposits() > hardcap);
// 1% fee for withdrawing after the crowdsale has ended or after the bonus period.
if (cap_reached || (now > time_bought + 1 days)) {
fee = pay_amount / 100;
}
// Send the funds. Throws on failure to prevent loss of funds.
token.transfer(msg.sender, pay_amount - fee);
token.transfer(developer, fee);
}
}
// Allow anyone to contribute to the buy execution bounty.
function add_to_bounty() payable {
// Disallow adding to the bounty if contract has already bought the tokens.
if (bought_tokens) throw;
// Update bounty to include received amount.
bounty += msg.value;
}
// Buys tokens in the crowdsale and rewards the caller, callable by anyone.
function buy(){
// Short circuit to save gas if the contract has already bought tokens.
if (bought_tokens) return;
// Record that the contract has bought the tokens.
bought_tokens = true;
// Record the time the contract bought the tokens.
time_bought = now;
// Transfer all the funds (less the bounty) to the TenX crowdsale contract
// to buy tokens. Throws if the crowdsale hasn't started yet or has
// already completed, preventing loss of funds.
sale.createTokens.value(this.balance - bounty)(address(this));
// Send the caller their bounty for buying tokens for the contract.
msg.sender.transfer(bounty);
}
// A helper function for the default function, allowing contracts to interact.
function default_helper() payable {
// Treat 0 ETH transactions as withdrawal requests.
if (msg.value == 0) {
withdraw();
}
// Otherwise, the user is sending funds to buy tokens.
else {
// Only allow deposits if the contract hasn't already purchased the tokens.
if (bought_tokens) throw;
// Update records of deposited ETH to include the received amount.
balances[msg.sender] += msg.value;
}
}
function () payable {
default_helper();
}
} | Allow anyone to contribute to the buy execution bounty. Disallow adding to the bounty if contract has already bought the tokens. Update bounty to include received amount. | function add_to_bounty() payable {
if (bought_tokens) throw;
bounty += msg.value;
}
| 2,216,231 |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity =0.6.10;
import {Ownable} from "../packages/oz/Ownable.sol";
import {OwnedUpgradeabilityProxy} from "../packages/oz/upgradeability/OwnedUpgradeabilityProxy.sol";
/**
* @author Opyn Team
* @title AddressBook Module
*/
contract AddressBook is Ownable {
/// @dev Otoken implementation key
bytes32 private constant OTOKEN_IMPL = keccak256("OTOKEN_IMPL");
/// @dev OtokenFactory key
bytes32 private constant OTOKEN_FACTORY = keccak256("OTOKEN_FACTORY");
/// @dev Whitelist key
bytes32 private constant WHITELIST = keccak256("WHITELIST");
/// @dev Controller key
bytes32 private constant CONTROLLER = keccak256("CONTROLLER");
/// @dev MarginPool key
bytes32 private constant MARGIN_POOL = keccak256("MARGIN_POOL");
/// @dev MarginCalculator key
bytes32 private constant MARGIN_CALCULATOR = keccak256("MARGIN_CALCULATOR");
/// @dev LiquidationManager key
bytes32 private constant LIQUIDATION_MANAGER = keccak256("LIQUIDATION_MANAGER");
/// @dev Oracle key
bytes32 private constant ORACLE = keccak256("ORACLE");
/// @dev mapping between key and address
mapping(bytes32 => address) private addresses;
/// @notice emits an event when a new proxy is created
event ProxyCreated(bytes32 indexed id, address indexed proxy);
/// @notice emits an event when a new address is added
event AddressAdded(bytes32 indexed id, address indexed add);
/**
* @notice return Otoken implementation address
* @return Otoken implementation address
*/
function getOtokenImpl() external view returns (address) {
return getAddress(OTOKEN_IMPL);
}
/**
* @notice return oTokenFactory address
* @return OtokenFactory address
*/
function getOtokenFactory() external view returns (address) {
return getAddress(OTOKEN_FACTORY);
}
/**
* @notice return Whitelist address
* @return Whitelist address
*/
function getWhitelist() external view returns (address) {
return getAddress(WHITELIST);
}
/**
* @notice return Controller address
* @return Controller address
*/
function getController() external view returns (address) {
return getAddress(CONTROLLER);
}
/**
* @notice return MarginPool address
* @return MarginPool address
*/
function getMarginPool() external view returns (address) {
return getAddress(MARGIN_POOL);
}
/**
* @notice return MarginCalculator address
* @return MarginCalculator address
*/
function getMarginCalculator() external view returns (address) {
return getAddress(MARGIN_CALCULATOR);
}
/**
* @notice return LiquidationManager address
* @return LiquidationManager address
*/
function getLiquidationManager() external view returns (address) {
return getAddress(LIQUIDATION_MANAGER);
}
/**
* @notice return Oracle address
* @return Oracle address
*/
function getOracle() external view returns (address) {
return getAddress(ORACLE);
}
/**
* @notice set Otoken implementation address
* @dev can only be called by the addressbook owner
* @param _otokenImpl Otoken implementation address
*/
function setOtokenImpl(address _otokenImpl) external onlyOwner {
setAddress(OTOKEN_IMPL, _otokenImpl);
}
/**
* @notice set OtokenFactory address
* @dev can only be called by the addressbook owner
* @param _otokenFactory OtokenFactory address
*/
function setOtokenFactory(address _otokenFactory) external onlyOwner {
setAddress(OTOKEN_FACTORY, _otokenFactory);
}
/**
* @notice set Whitelist address
* @dev can only be called by the addressbook owner
* @param _whitelist Whitelist address
*/
function setWhitelist(address _whitelist) external onlyOwner {
setAddress(WHITELIST, _whitelist);
}
/**
* @notice set Controller address
* @dev can only be called by the addressbook owner
* @param _controller Controller address
*/
function setController(address _controller) external onlyOwner {
updateImpl(CONTROLLER, _controller);
}
/**
* @notice set MarginPool address
* @dev can only be called by the addressbook owner
* @param _marginPool MarginPool address
*/
function setMarginPool(address _marginPool) external onlyOwner {
setAddress(MARGIN_POOL, _marginPool);
}
/**
* @notice set MarginCalculator address
* @dev can only be called by the addressbook owner
* @param _marginCalculator MarginCalculator address
*/
function setMarginCalculator(address _marginCalculator) external onlyOwner {
setAddress(MARGIN_CALCULATOR, _marginCalculator);
}
/**
* @notice set LiquidationManager address
* @dev can only be called by the addressbook owner
* @param _liquidationManager LiquidationManager address
*/
function setLiquidationManager(address _liquidationManager) external onlyOwner {
setAddress(LIQUIDATION_MANAGER, _liquidationManager);
}
/**
* @notice set Oracle address
* @dev can only be called by the addressbook owner
* @param _oracle Oracle address
*/
function setOracle(address _oracle) external onlyOwner {
setAddress(ORACLE, _oracle);
}
/**
* @notice return an address for specific key
* @param _key key address
* @return address
*/
function getAddress(bytes32 _key) public view returns (address) {
return addresses[_key];
}
/**
* @notice set a specific address for a specific key
* @dev can only be called by the addressbook owner
* @param _key key
* @param _address address
*/
function setAddress(bytes32 _key, address _address) public onlyOwner {
addresses[_key] = _address;
emit AddressAdded(_key, _address);
}
/**
* @dev function to update the implementation of a specific component of the protocol
* @param _id id of the contract to be updated
* @param _newAddress address of the new implementation
**/
function updateImpl(bytes32 _id, address _newAddress) public onlyOwner {
address payable proxyAddress = address(uint160(getAddress(_id)));
if (proxyAddress == address(0)) {
bytes memory params = abi.encodeWithSignature("initialize(address,address)", address(this), owner());
OwnedUpgradeabilityProxy proxy = new OwnedUpgradeabilityProxy();
setAddress(_id, address(proxy));
emit ProxyCreated(_id, address(proxy));
proxy.upgradeToAndCall(_newAddress, params);
} else {
OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(proxyAddress);
proxy.upgradeTo(_newAddress);
}
}
}
| return Whitelist address return Whitelist address/ | function getWhitelist() external view returns (address) {
return getAddress(WHITELIST);
}
| 950,568 |
./full_match/3/0xC883346258766Aa025f6705922150EBe8566A259/sources/_aave/core-v3/contracts/protocol/pool/PoolConfigurator.sol | @inheritdoc IPoolConfigurator | function setReserveStableRateBorrowing(address asset, bool enabled)
external
override
onlyRiskOrPoolAdmins
{
DataTypes.ReserveConfigurationMap memory currentConfig = _pool.getConfiguration(asset);
if (enabled) {
require(currentConfig.getBorrowingEnabled(), Errors.BORROWING_NOT_ENABLED);
}
currentConfig.setStableRateBorrowingEnabled(enabled);
_pool.setConfiguration(asset, currentConfig);
emit ReserveStableRateBorrowing(asset, enabled);
}
| 14,155,200 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
}
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface ERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ENOStaking is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeMath for uint256;
using SafeMath for uint8;
struct Stake{
uint deposit_amount; //Deposited Amount
uint stake_creation_time; //The time when the stake was created
bool returned; //Specifies if the funds were withdrawed
uint alreadyWithdrawedAmount; //TODO Correct Lint
}
struct Account{
address referral;
uint referralAlreadyWithdrawed;
}
//---------------------------------------------------------------------
//-------------------------- EVENTS -----------------------------------
//---------------------------------------------------------------------
/**
* @dev Emitted when the pot value changes
*/
event PotUpdated(
uint newPot
);
/**
* @dev Emitted when a customer tries to withdraw an amount
* of token greater than the one in the pot
*/
event PotExhausted(
);
/**
* @dev Emitted when a new stake is issued
*/
event NewStake(
uint stakeAmount,
address from
);
/**
* @dev Emitted when a new stake is withdrawed
*/
event StakeWithdraw(
uint stakeID,
uint amount
);
/**
* @dev Emitted when a referral reward is sent
*/
event referralRewardSent(
address account,
uint reward
);
event rewardWithdrawed(
address account
);
/**
* @dev Emitted when the machine is stopped (500.000 tokens)
*/
event machineStopped(
);
/**
* @dev Emitted when the subscription is stopped (400.000 tokens)
*/
event subscriptionStopped(
);
//--------------------------------------------------------------------
//-------------------------- GLOBALS -----------------------------------
//--------------------------------------------------------------------
mapping (address => Stake[]) private stake; /// @dev Map that contains account's stakes
address private tokenAddress;
ERC20 private ERC20Interface;
uint private pot; //The pot where token are taken
uint256 private amount_supplied; //Store the remaining token to be supplied
uint private pauseTime; //Time when the machine paused
uint private stopTime; //Time when the machine stopped
// @dev Mapping the referrals
mapping (address => address[]) private referral; //Store account that used the referral
mapping (address => Account) private account_referral; //Store the setted account referral
address[] private activeAccounts; //Store both staker and referer address
uint256 private constant _DECIMALS = 18;
uint256 private constant _INTEREST_PERIOD = 1 days; //One Month
uint256 private constant _INTEREST_VALUE = 333; //0.333% per day
uint256 private constant _PENALTY_VALUE = 20; //20% of the total stake
uint256 private constant _MIN_STAKE_AMOUNT = 100 * (10**_DECIMALS);
uint256 private constant _MAX_STAKE_AMOUNT = 100000 * (10**_DECIMALS);
uint private constant _REFERALL_REWARD = 333; //0.333% per day
uint256 private constant _MAX_TOKEN_SUPPLY_LIMIT = 50000000 * (10**_DECIMALS);
uint256 private constant _MIDTERM_TOKEN_SUPPLY_LIMIT = 40000000 * (10**_DECIMALS);
constructor() {
pot = 0;
amount_supplied = _MAX_TOKEN_SUPPLY_LIMIT; //The total amount of token released
tokenAddress = address(0);
}
//--------------------------------------------------------------------
//-------------------------- TOKEN ADDRESS -----------------------------------
//--------------------------------------------------------------------
function setTokenAddress(address _tokenAddress) external onlyOwner {
require(Address.isContract(_tokenAddress), "The address does not point to a contract");
tokenAddress = _tokenAddress;
ERC20Interface = ERC20(tokenAddress);
}
function isTokenSet() external view returns (bool) {
if(tokenAddress == address(0))
return false;
return true;
}
function getTokenAddress() external view returns (address){
return tokenAddress;
}
//--------------------------------------------------------------------
//-------------------------- ONLY OWNER -----------------------------------
//--------------------------------------------------------------------
function depositPot(uint _amount) external onlyOwner nonReentrant {
require(tokenAddress != address(0), "The Token Contract is not specified");
pot = pot.add(_amount);
if(ERC20Interface.transferFrom(msg.sender, address(this), _amount)){
//Emit the event to update the UI
emit PotUpdated(pot);
}else{
revert("Unable to tranfer funds");
}
}
function returnPot(uint _amount) external onlyOwner nonReentrant{
require(tokenAddress != address(0), "The Token Contract is not specified");
require(pot.sub(_amount) >= 0, "Not enough token");
pot = pot.sub(_amount);
if(ERC20Interface.transfer(msg.sender, _amount)){
//Emit the event to update the UI
emit PotUpdated(pot);
}else{
revert("Unable to tranfer funds");
}
}
function finalShutdown() external onlyOwner nonReentrant{
uint machineAmount = getMachineBalance();
if(!ERC20Interface.transfer(owner(), machineAmount)){
revert("Unable to transfer funds");
}
//Goodbye
}
function getAllAccount() external onlyOwner view returns (address[] memory){
return activeAccounts;
}
/**
* @dev Check if the pot has enough balance to satisfy the potential withdraw
*/
function getPotentialWithdrawAmount() external onlyOwner view returns (uint){
uint accountNumber = activeAccounts.length;
uint potentialAmount = 0;
for(uint i = 0; i<accountNumber; i++){
address currentAccount = activeAccounts[i];
potentialAmount = potentialAmount.add(calculateTotalRewardReferral(currentAccount)); //Referral
potentialAmount = potentialAmount.add(calculateTotalRewardToWithdraw(currentAccount)); //Normal Reward
}
return potentialAmount;
}
//--------------------------------------------------------------------
//-------------------------- CLIENTS -----------------------------------
//--------------------------------------------------------------------
/**
* @dev Stake token verifying all the contraint
* @notice Stake tokens
* @param _amount Amoun to stake
* @param _referralAddress Address of the referer; 0x000...1 if no referer is provided
*/
function stakeToken(uint _amount, address _referralAddress) external nonReentrant {
require(tokenAddress != address(0), "No contract set");
require(_amount >= _MIN_STAKE_AMOUNT, "You must stake at least 100 tokens");
require(_amount <= _MAX_STAKE_AMOUNT, "You must stake at maximum 100000 tokens");
require(!isSubscriptionEnded(), "Subscription ended");
address staker = msg.sender;
Stake memory newStake;
newStake.deposit_amount = _amount;
newStake.returned = false;
newStake.stake_creation_time = block.timestamp;
newStake.alreadyWithdrawedAmount = 0;
stake[staker].push(newStake);
if(!hasReferral()){
setReferral(_referralAddress);
}
activeAccounts.push(msg.sender);
if(ERC20Interface.transferFrom(msg.sender, address(this), _amount)){
emit NewStake(_amount, _referralAddress);
}else{
revert("Unable to transfer funds");
}
}
/**
* @dev Return the staked tokens, requiring that the stake was
* not alreay withdrawed
* @notice Return staked token
* @param _stakeID The ID of the stake to be returned
*/
function returnTokens(uint _stakeID) external nonReentrant returns (bool){
Stake memory selectedStake = stake[msg.sender][_stakeID];
//Check if the stake were already withdraw
require(selectedStake.returned == false, "Stake were already returned");
uint deposited_amount = selectedStake.deposit_amount;
//Get the net reward
uint penalty = calculatePenalty(deposited_amount);
//Sum the net reward to the total reward to withdraw
uint total_amount = deposited_amount.sub(penalty);
//Update the supplied amount considering also the penalty
uint supplied = deposited_amount.sub(total_amount);
require(updateSuppliedToken(supplied), "Limit reached");
//Add the penalty to the pot
pot = pot.add(penalty);
//Only set the withdraw flag in order to disable further withdraw
stake[msg.sender][_stakeID].returned = true;
if(ERC20Interface.transfer(msg.sender, total_amount)){
emit StakeWithdraw(_stakeID, total_amount);
}else{
revert("Unable to transfer funds");
}
return true;
}
function withdrawReward(uint _stakeID) external nonReentrant returns (bool){
Stake memory _stake = stake[msg.sender][_stakeID];
uint rewardToWithdraw = calculateRewardToWithdraw(_stakeID);
require(updateSuppliedToken(rewardToWithdraw), "Supplied limit reached");
if(rewardToWithdraw > pot){
revert("Pot exhausted");
}
pot = pot.sub(rewardToWithdraw);
stake[msg.sender][_stakeID].alreadyWithdrawedAmount = _stake.alreadyWithdrawedAmount.add(rewardToWithdraw);
if(ERC20Interface.transfer(msg.sender, rewardToWithdraw)){
emit rewardWithdrawed(msg.sender);
}else{
revert("Unable to transfer funds");
}
return true;
}
function withdrawReferralReward() external nonReentrant returns (bool){
uint referralCount = referral[msg.sender].length;
uint totalAmount = 0;
for(uint i = 0; i<referralCount; i++){
address currentAccount = referral[msg.sender][i];
uint currentReward = calculateRewardReferral(currentAccount);
totalAmount = totalAmount.add(currentReward);
//Update the alreadyWithdrawed status
account_referral[currentAccount].referralAlreadyWithdrawed = account_referral[currentAccount].referralAlreadyWithdrawed.add(currentReward);
}
require(updateSuppliedToken(totalAmount), "Machine limit reached");
//require(withdrawFromPot(totalAmount), "Pot exhausted");
if(totalAmount > pot){
revert("Pot exhausted");
}
pot = pot.sub(totalAmount);
if(ERC20Interface.transfer(msg.sender, totalAmount)){
emit referralRewardSent(msg.sender, totalAmount);
}else{
revert("Unable to transfer funds");
}
return true;
}
/**
* @dev Check if the provided amount is available in the pot
* If yes, it will update the pot value and return true
* Otherwise it will emit a PotExhausted event and return false
*/
function withdrawFromPot(uint _amount) public nonReentrant returns (bool){
if(_amount > pot){
emit PotExhausted();
return false;
}
//Update the pot value
pot = pot.sub(_amount);
return true;
}
//--------------------------------------------------------------------
//-------------------------- VIEWS -----------------------------------
//--------------------------------------------------------------------
/**
* @dev Return the amount of token in the provided caller's stake
* @param _stakeID The ID of the stake of the caller
*/
function getCurrentStakeAmount(uint _stakeID) external view returns (uint256) {
require(tokenAddress != address(0), "No contract set");
return stake[msg.sender][_stakeID].deposit_amount;
}
/**
* @dev Return sum of all the caller's stake amount
* @return Amount of stake
*/
function getTotalStakeAmount() external view returns (uint256) {
require(tokenAddress != address(0), "No contract set");
Stake[] memory currentStake = stake[msg.sender];
uint nummberOfStake = stake[msg.sender].length;
uint totalStake = 0;
uint tmp;
for (uint i = 0; i<nummberOfStake; i++){
tmp = currentStake[i].deposit_amount;
totalStake = totalStake.add(tmp);
}
return totalStake;
}
/**
* @dev Return all the available stake info
* @notice Return stake info
* @param _stakeID ID of the stake which info is returned
*
* @return 1) Amount Deposited
* @return 2) Bool value that tells if the stake was withdrawed
* @return 3) Stake creation time (Unix timestamp)
* @return 4) The eventual referAccountess != address(0), "No contract set");
* @return 5) The current amount
* @return 6) The penalty of withdraw
*/
function getStakeInfo(uint _stakeID) external view returns(uint, bool, uint, address, uint, uint){
Stake memory selectedStake = stake[msg.sender][_stakeID];
uint amountToWithdraw = calculateRewardToWithdraw(_stakeID);
uint penalty = calculatePenalty(selectedStake.deposit_amount);
address myReferral = getMyReferral();
return (
selectedStake.deposit_amount,
selectedStake.returned,
selectedStake.stake_creation_time,
myReferral,
amountToWithdraw,
penalty
);
}
/**
* @dev Get the current pot value
* @return The amount of token in the current pot
*/
function getCurrentPot() external view returns (uint){
return pot;
}
/**
* @dev Get the number of active stake of the caller
* @return Number of active stake
*/
function getStakeCount() external view returns (uint){
return stake[msg.sender].length;
}
function getActiveStakeCount() external view returns(uint){
uint stakeCount = stake[msg.sender].length;
uint count = 0;
for(uint i = 0; i<stakeCount; i++){
if(!stake[msg.sender][i].returned){
count = count + 1;
}
}
return count;
}
function getReferralCount() external view returns (uint) {
return referral[msg.sender].length;
}
function getAccountReferral() external view returns (address[] memory){
return referral[msg.sender];
}
function getAlreadyWithdrawedAmount(uint _stakeID) external view returns (uint){
return stake[msg.sender][_stakeID].alreadyWithdrawedAmount;
}
//--------------------------------------------------------------------
//-------------------------- REFERRALS -----------------------------------
//--------------------------------------------------------------------
function hasReferral() public view returns (bool){
Account memory myAccount = account_referral[msg.sender];
if(myAccount.referral == address(0) || myAccount.referral == address(0x0000000000000000000000000000000000000001)){
//If I have no referral...
assert(myAccount.referralAlreadyWithdrawed == 0);
return false;
}
return true;
}
function getMyReferral() public view returns (address){
Account memory myAccount = account_referral[msg.sender];
return myAccount.referral;
}
function setReferral(address referer) internal {
require(referer != address(0), "Invalid address");
require(!hasReferral(), "Referral already setted");
if(referer == address(0x0000000000000000000000000000000000000001)){
return; //This means no referer
}
if(referer == msg.sender){
revert("Referral is the same as the sender, forbidden");
}
referral[referer].push(msg.sender);
Account memory account;
account.referral = referer;
account.referralAlreadyWithdrawed = 0;
account_referral[msg.sender] = account;
activeAccounts.push(referer); //Add to the list of active account for pot calculation
}
function getCurrentReferrals() external view returns (address[] memory){
return referral[msg.sender];
}
/**
* @dev Calculate the current referral reward of the specified customer
* @return The amount of referral reward related to the given customer
*/
function calculateRewardReferral(address customer) public view returns (uint){
uint lowestStake;
uint lowStakeID;
(lowestStake, lowStakeID) = getLowestStake(customer);
if(lowestStake == 0 && lowStakeID == 0){
return 0;
}
uint periods = calculateAccountStakePeriods(customer, lowStakeID);
uint currentReward = lowestStake.mul(_REFERALL_REWARD).mul(periods).div(100000);
uint alreadyWithdrawed = account_referral[customer].referralAlreadyWithdrawed;
if(currentReward <= alreadyWithdrawed){
return 0; //Already withdrawed all the in the past
}
uint availableReward = currentReward.sub(alreadyWithdrawed);
return availableReward;
}
function calculateTotalRewardReferral() external view returns (uint){
uint referralCount = referral[msg.sender].length;
uint totalAmount = 0;
for(uint i = 0; i<referralCount; i++){
totalAmount = totalAmount.add(calculateRewardReferral(referral[msg.sender][i]));
}
return totalAmount;
}
function calculateTotalRewardReferral(address _account) public view returns (uint){
uint referralCount = referral[_account].length;
uint totalAmount = 0;
for(uint i = 0; i<referralCount; i++){
totalAmount = totalAmount.add(calculateRewardReferral(referral[_account][i]));
}
return totalAmount;
}
/**
* @dev Returns the lowest stake info of the current account
* @param customer Customer where the lowest stake is returned
* @return uint The stake amount
* @return uint The stake ID
*/
function getLowestStake(address customer) public view returns (uint, uint){
uint stakeNumber = stake[customer].length;
uint min = _MAX_STAKE_AMOUNT;
uint minID = 0;
bool foundFlag = false;
for(uint i = 0; i<stakeNumber; i++){
if(stake[customer][i].deposit_amount <= min){
if(stake[customer][i].returned){
continue;
}
min = stake[customer][i].deposit_amount;
minID = i;
foundFlag = true;
}
}
if(!foundFlag){
return (0, 0);
}else{
return (min, minID);
}
}
//--------------------------------------------------------------------
//-------------------------- INTERNAL -----------------------------------
//--------------------------------------------------------------------
/**
* @dev Calculate the customer reward based on the provided stake
* param uint _stakeID The stake where the reward should be calculated
* @return The reward value
*/
function calculateRewardToWithdraw(uint _stakeID) public view returns (uint){
Stake memory _stake = stake[msg.sender][_stakeID];
uint amount_staked = _stake.deposit_amount;
uint already_withdrawed = _stake.alreadyWithdrawedAmount;
uint periods = calculatePeriods(_stakeID); //Periods for interest calculation
uint interest = amount_staked.mul(_INTEREST_VALUE);
uint total_interest = interest.mul(periods).div(100000);
uint reward = total_interest.sub(already_withdrawed); //Subtract the already withdrawed amount
return reward;
}
function calculateRewardToWithdraw(address _account, uint _stakeID) internal view onlyOwner returns (uint){
Stake memory _stake = stake[_account][_stakeID];
uint amount_staked = _stake.deposit_amount;
uint already_withdrawed = _stake.alreadyWithdrawedAmount;
uint periods = calculateAccountStakePeriods(_account, _stakeID); //Periods for interest calculation
uint interest = amount_staked.mul(_INTEREST_VALUE);
uint total_interest = interest.mul(periods).div(100000);
uint reward = total_interest.sub(already_withdrawed); //Subtract the already withdrawed amount
return reward;
}
function calculateTotalRewardToWithdraw(address _account) internal view onlyOwner returns (uint){
Stake[] memory accountStakes = stake[_account];
uint stakeNumber = accountStakes.length;
uint amount = 0;
for( uint i = 0; i<stakeNumber; i++){
amount = amount.add(calculateRewardToWithdraw(_account, i));
}
return amount;
}
function calculateCompoundInterest(uint _stakeID) external view returns (uint256){
Stake memory _stake = stake[msg.sender][_stakeID];
uint256 periods = calculatePeriods(_stakeID);
uint256 amount_staked = _stake.deposit_amount;
uint256 excepted_amount = amount_staked;
//Calculate reward
for(uint i = 0; i < periods; i++){
uint256 period_interest;
period_interest = excepted_amount.mul(_INTEREST_VALUE).div(100);
excepted_amount = excepted_amount.add(period_interest);
}
assert(excepted_amount >= amount_staked);
return excepted_amount;
}
function calculatePeriods(uint _stakeID) public view returns (uint){
Stake memory _stake = stake[msg.sender][_stakeID];
uint creation_time = _stake.stake_creation_time;
uint current_time = block.timestamp;
uint total_period = current_time.sub(creation_time);
uint periods = total_period.div(_INTEREST_PERIOD);
return periods;
}
function calculateAccountStakePeriods(address _account, uint _stakeID) public view returns (uint){
Stake memory _stake = stake[_account][_stakeID];
uint creation_time = _stake.stake_creation_time;
uint current_time = block.timestamp;
uint total_period = current_time.sub(creation_time);
uint periods = total_period.div(_INTEREST_PERIOD);
return periods;
}
function calculatePenalty(uint _amountStaked) private pure returns (uint){
uint tmp_penalty = _amountStaked.mul(_PENALTY_VALUE); //Take the 10 percent
return tmp_penalty.div(100);
}
function updateSuppliedToken(uint _amount) internal returns (bool){
if(_amount > amount_supplied){
return false;
}
amount_supplied = amount_supplied.sub(_amount);
return true;
}
function checkPotBalance(uint _amount) internal view returns (bool){
if(pot >= _amount){
return true;
}
return false;
}
function getMachineBalance() internal view returns (uint){
return ERC20Interface.balanceOf(address(this));
}
function getMachineState() external view returns (uint){
return amount_supplied;
}
function isSubscriptionEnded() public view returns (bool){
if(amount_supplied >= _MAX_TOKEN_SUPPLY_LIMIT - _MIDTERM_TOKEN_SUPPLY_LIMIT){
return false;
}else{
return true;
}
}
function isMachineStopped() public view returns (bool){
if(amount_supplied > 0){
return true;
}else{
return false;
}
}
//--------------------------------------------------------------
//------------------------ DEBUG -------------------------------
//--------------------------------------------------------------
function getOwner() external view returns (address){
return owner();
}
} | Update the alreadyWithdrawed status | function withdrawReferralReward() external nonReentrant returns (bool){
uint referralCount = referral[msg.sender].length;
uint totalAmount = 0;
for(uint i = 0; i<referralCount; i++){
address currentAccount = referral[msg.sender][i];
uint currentReward = calculateRewardReferral(currentAccount);
totalAmount = totalAmount.add(currentReward);
account_referral[currentAccount].referralAlreadyWithdrawed = account_referral[currentAccount].referralAlreadyWithdrawed.add(currentReward);
}
require(updateSuppliedToken(totalAmount), "Machine limit reached");
if(totalAmount > pot){
revert("Pot exhausted");
}
pot = pot.sub(totalAmount);
if(ERC20Interface.transfer(msg.sender, totalAmount)){
emit referralRewardSent(msg.sender, totalAmount);
revert("Unable to transfer funds");
}
return true;
}
| 7,030,858 |
// SPDX-License-Identifier: CC 0
pragma solidity ^0.8.0;
interface faucetInterface {
function send(address des) external;
}
interface adminInterface {
function voteTo(address votorAddress, Vote votingAddress) external;
function rightTo(address votorAddress, Vote votingAddress) external;
}
contract Vote {
address public chairperson;
bytes32 public name;
Proposal[] public proposals;
mapping(address => Voter) public voters;
uint public createTime;
bool public ended;
uint public endTime;
address public adminAddress;
address public faucetAddress;
faucetInterface faucetInstance;
adminInterface adminInstance;
struct Voter {
bool voted;
uint8 weight;
uint8 vote;
uint voteTime;
}
struct Proposal {
bytes32 name;
uint voteCount;
}
/// You will create a vote named `voteName`.
/// You can't edit this name later.
constructor(address sendChairperson, bytes32 voteName, address admin, address faucet) {
name = voteName;
chairperson = sendChairperson;
voters[chairperson].weight = 1;
ended = false;
createTime = block.timestamp;
adminAddress = admin;
faucetAddress = faucet;
faucetInstance = faucetInterface(faucetAddress);
adminInstance = adminInterface(adminAddress);
}
/// Only can use by chairperson.
/// You will create a new proposal named `proposalName`.
/// You can edit this name later.
function newProposal(bytes32 proposalName) public {
require(msg.sender == chairperson, "Only Chairperson can do this.");
require(!ifEnded(), "This voting had ended.");
proposals.push(Proposal({
name: proposalName,
voteCount: 0
}));
}
/// Only can use by chairperson.
/// You will create `proposalsName.length` proposals.
function newProposals(bytes32[] memory proposalsName) public {
require(msg.sender == chairperson, "Only Chairperson can do this.");
require(!ifEnded(), "This voting had ended.");
for (uint i = 0; i < proposalsName.length; i++) {
newProposal(proposalsName[i]);
}
}
/// Only can use by chairperson.
/// You will change a proposal's name from `proposals[proposalNumber].name` to `newProposalName`.
function setProposal(uint proposalNumber, bytes32 newProposalName) public {
require(msg.sender == chairperson, "Only Chairperson can do this.");
require(!ifEnded(), "This voting had ended.");
proposals[proposalNumber].name = newProposalName;
}
/// Only can use by chairperson.
/// You will set end time for this vote.
/// You only can set a time after now, and no way to cancel.
/// No way to reopen this voting after it is ended.
function setEndTime(uint newEndTime) public {
require(msg.sender == chairperson, "Only Chairperson can do this.");
require(!ifEnded(), "This voting had ended.");
require(block.timestamp < newEndTime, "End time should later than now.");
endTime = newEndTime;
}
/// Only can use by chairperson.
/// You will get Voting-right to `person`.
/// No way to cancel the right.
function giveRightTo(address person) public {
require(msg.sender == chairperson, "Only Chairperson can do this.");
voters[person].weight = 1;
adminInstance.rightTo(person, this);
if (person.balance <= 1000000000000 wei) {
faucetInstance.send(person);
}
}
/// You will vote to `proposals[proposalNumber].name`
/// You can't switch to another proposal later.
function vote(uint proposalNumber) public {
require(!ifEnded(), "This voting had ended.");
require(voters[msg.sender].weight != 0, "You should get the voting right from chairperson.");
require(!voters[msg.sender].voted, "You had voted.");
proposals[proposalNumber].voteCount += 1;
voters[msg.sender].voted = true;
voters[msg.sender].voteTime = block.timestamp;
adminInstance.voteTo(msg.sender, this);
}
/// You will get the wining proposal of this voting.
function getWinner() public view returns (uint winnerNumber) {
uint winnerVoteCount;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > winnerVoteCount) {
winnerNumber = i;
winnerVoteCount = proposals[i].voteCount;
}
}
}
function ifEnded() private returns(bool isEnded) {
if (ended) {
isEnded = true;
} else if (block.timestamp > endTime && endTime != 0) {
ended = true;
isEnded = true;
} else {
isEnded = false;
}
}
/// You will end this voting.
/// If you do not set end time, you can end it any time.
/// If you have set end time, you only can end it after end time.
/// No way to reopen this voting.
function endVote() public returns (uint winnerNumber) {
require(!ifEnded(), "This voting had ended.");
if (endTime == 0) {
require(msg.sender == chairperson, "Only Chairperson can do this.");
} else {
require(block.timestamp > endTime, "You only can end this voting after end time.");
}
ended = true;
winnerNumber = getWinner();
}
receive() external payable {}
fallback() external payable {}
}
contract VoteAdmin {
address public defaultAdminAddress;
address public defaultFaucetAddress;
address public administor;
mapping(address => Vote[]) public created;
mapping(address => Vote[]) public voted;
mapping(address => Vote[]) public righted;
constructor() {
administor = msg.sender;
}
function create(bytes32 votingName) public returns (Vote votingAddress) {
votingAddress = new Vote(msg.sender, votingName, defaultAdminAddress, defaultFaucetAddress);
created[msg.sender].push(votingAddress);
}
function voteTo(address votorAddress, Vote votingAddress) public {
voted[votorAddress].push(votingAddress);
}
function rightTo(address votorAddress, Vote votingAddress) public {
righted[votorAddress].push(votingAddress);
}
function setAdmin(address admin) public {
defaultAdminAddress = admin;
}
function setFaucet(address faucet) public {
defaultFaucetAddress = faucet;
}
function getCreated() public view returns (Vote[] memory votes) {
votes = created[msg.sender];
}
function getVoted() public view returns (Vote[] memory votes) {
votes = voted[msg.sender];
}
function getRighted() public view returns (Vote[] memory votes) {
votes = righted[msg.sender];
}
} | Only can use by chairperson. You will create a new proposal named `proposalName`. You can edit this name later. | function newProposal(bytes32 proposalName) public {
require(msg.sender == chairperson, "Only Chairperson can do this.");
require(!ifEnded(), "This voting had ended.");
proposals.push(Proposal({
name: proposalName,
voteCount: 0
}));
}
| 1,028,513 |
//*********************************************************************//
//*********************************************************************//
//
// ____ _ __ ___ __ ____ ____
// / __ )(_)___ _/ |/ /___ ____ ___ ____ ___ __ __/ |/ (_) / /_____ __________
// / __ / / __ `/ /|_/ / __ \/ __ `__ \/ __ `__ \/ / / / /|_/ / / / //_/ _ \/ ___/ ___/
// / /_/ / / /_/ / / / / /_/ / / / / / / / / / / / /_/ / / / / / / ,< / __/ / (__ )
// /_____/_/\__, /_/ /_/\____/_/ /_/ /_/_/ /_/ /_/\__, /_/ /_/_/_/_/|_|\___/_/ /____/
// /____/ /____/
//
//*********************************************************************//
//*********************************************************************//
//-------------DEPENDENCIES--------------------------//
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// 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;
}
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if account is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, isContract will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on isContract to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's transfer: sends amount wei to
* recipient, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by transfer, making them unable to receive funds via
* transfer. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to recipient, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level call. A
* plain call is an unsafe replacement for a function call: use this
* function instead.
*
* If target reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode].
*
* Requirements:
*
* - target must be a contract.
* - calling target with data must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with
* errorMessage as a fallback revert reason when target reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but also transferring value wei to target.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least value.
* - the called Solidity function must be payable.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but
* with errorMessage as a fallback revert reason when target reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} tokenId token is transferred to this contract via {IERC721-safeTransferFrom}
* by operator from from, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with IERC721.onERC721Received.selector.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* interfaceId. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
*
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when tokenId token is transferred from from to to.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when owner enables approved to manage the tokenId token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when owner enables or disables (approved) operator to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in owner's account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the tokenId token.
*
* Requirements:
*
* - tokenId must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers tokenId token from from to to, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must exist and be owned by from.
* - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers tokenId token from from to to.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must be owned by from.
* - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to to to transfer tokenId token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - tokenId must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for tokenId token.
*
* Requirements:
*
* - tokenId must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove operator as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The operator cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the operator is allowed to manage all of the assets of owner.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers tokenId token from from to to.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must exist and be owned by from.
* - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by owner at a given index of its token list.
* Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for tokenId token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a uint256 to its ASCII string decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a uint256 to its ASCII string hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a uint256 to its ASCII string hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from ReentrancyGuard will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single nonReentrant guard, functions marked as
* nonReentrant may not call one another. This can be worked around by making
* those functions private, and then adding external nonReentrant entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a nonReentrant function from another nonReentrant
* function is not supported. It is possible to prevent this from happening
* by making the nonReentrant function external, and making it call a
* private function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* onlyOwner, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* onlyOwner functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (newOwner).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (newOwner).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//-------------END DEPENDENCIES------------------------//
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex;
uint256 public immutable collectionSize;
uint256 public maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* maxBatchSize refers to how much a minter can mint at a time.
* collectionSize_ refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 1;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalMinted();
}
function currentTokenId() public view returns (uint256) {
return _totalMinted();
}
function getNextTokenId() public view returns (uint256) {
return SafeMath.add(_totalMinted(), 1);
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
unchecked {
return currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the baseURI and the tokenId. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether tokenId exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (_mint),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints quantity tokens and transfers them to to.
*
* Requirements:
*
* - there must be quantity tokens remaining unminted in the total collection.
* - to cannot be the zero address.
* - quantity cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers tokenId from from to to.
*
* Requirements:
*
* - to cannot be the zero address.
* - tokenId token must be owned by from.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve to to operate on tokenId
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set owners to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet');
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When from and to are both non-zero, from's tokenId will be
* transferred to to.
* - When from is zero, tokenId will be minted for to.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when from and to are both non-zero.
* - from and to are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
abstract contract Ramppable {
address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1;
modifier isRampp() {
require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP");
_;
}
}
interface IERC20 {
function transfer(address _to, uint256 _amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
abstract contract Withdrawable is Ownable, Ramppable {
address[] public payableAddresses = [RAMPPADDRESS,0x55728643F1c53f999Ca29E4DBd0E02245Da8D4cB];
uint256[] public payableFees = [5,95];
uint256 public payableAddressCount = 2;
function withdrawAll() public onlyOwner {
require(address(this).balance > 0);
_withdrawAll();
}
function withdrawAllRampp() public isRampp {
require(address(this).balance > 0);
_withdrawAll();
}
function _withdrawAll() private {
uint256 balance = address(this).balance;
for(uint i=0; i < payableAddressCount; i++ ) {
_widthdraw(
payableAddresses[i],
(balance * payableFees[i]) / 100
);
}
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
/**
* @dev Allow contract owner to withdraw ERC-20 balance from contract
* while still splitting royalty payments to all other team members.
* in the event ERC-20 tokens are paid to the contract.
* @param _tokenContract contract of ERC-20 token to withdraw
* @param _amount balance to withdraw according to balanceOf of ERC-20 token
*/
function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner {
require(_amount > 0);
IERC20 tokenContract = IERC20(_tokenContract);
require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens');
for(uint i=0; i < payableAddressCount; i++ ) {
tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100);
}
}
}
abstract contract RamppERC721A is
Ownable,
ERC721A,
Withdrawable,
ReentrancyGuard {
constructor(
string memory tokenName,
string memory tokenSymbol
) ERC721A(tokenName, tokenSymbol, 9, 969 ) {}
using SafeMath for uint256;
uint8 public CONTRACT_VERSION = 2;
string public _baseTokenURI = "ipfs://QmQ2TwFRLKn4bgyqW5YzNNKfQU77VoMBPnxep9VBTC7bmf/";
bool public mintingOpen = true;
bool public isRevealed = false;
uint256 public PRICE = 0.0069 ether;
/////////////// Admin Mint Functions
/**
* @dev Mints a token to an address with a tokenURI.
* This is owner only and allows a fee-free drop
* @param _to address of the future owner of the token
*/
function mintToAdmin(address _to) public onlyOwner {
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 969");
_safeMint(_to, 1);
}
function mintManyAdmin(address[] memory _addresses, uint256 _addressCount) public onlyOwner {
for(uint i=0; i < _addressCount; i++ ) {
mintToAdmin(_addresses[i]);
}
}
/////////////// GENERIC MINT FUNCTIONS
/**
* @dev Mints a single token to an address.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public payable {
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 969");
require(mintingOpen == true, "Minting is not open right now!");
require(msg.value == PRICE, "Value needs to be exactly the mint fee!");
_safeMint(_to, 1);
}
/**
* @dev Mints a token to an address with a tokenURI.
* fee may or may not be required*
* @param _to address of the future owner of the token
* @param _amount number of tokens to mint
*/
function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(mintingOpen == true, "Minting is not open right now!");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 969");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
}
function openMinting() public onlyOwner {
mintingOpen = true;
}
function stopMinting() public onlyOwner {
mintingOpen = false;
}
/**
* @dev Allows owner to set Max mints per tx
* @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1
*/
function setMaxMint(uint256 _newMaxMint) public onlyOwner {
require(_newMaxMint >= 1, "Max mint must be at least 1");
maxBatchSize = _newMaxMint;
}
function setPrice(uint256 _feeInWei) public onlyOwner {
PRICE = _feeInWei;
}
function getPrice(uint256 _count) private view returns (uint256) {
return PRICE.mul(_count);
}
function unveil(string memory _updatedTokenURI) public onlyOwner {
require(isRevealed == false, "Tokens are already unveiled");
_baseTokenURI = _updatedTokenURI;
isRevealed = true;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) {
return ownershipOf(tokenId);
}
}
// File: contracts/BigMommyMilkersContract.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract BigMommyMilkersContract is RamppERC721A {
constructor() RamppERC721A("BigMommyMilkers", "MommysMilk"){}
function contractURI() public pure returns (string memory) {
return "https://us-central1-nft-rampp.cloudfunctions.net/app/jO2fEOLZMewjzizsYzVK/contract-metadata";
}
}
//*********************************************************************//
//*********************************************************************//
// ___
// / _ \ ___ _ __ _ ___ ___
// / , _// _ `/ / ' \ / _ \ / _ \
// /_/|_| \_,_/ /_/_/_/ / .__/ / .__/.xyz
// /_/ /_/
// v2.0.1
//
// This smart contract was generated by rampp.xyz.
// Rampp allows creators like you to launch
// large scale NFT projects without code!
//
// Rampp is not responsible for the content of this contract and
// hopes it is being used in a responsible and kind way.
// Twitter: @RamppDAO ---- rampp.xyz
//*********************************************************************//
//*********************************************************************// | Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/ | function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(mintingOpen == true, "Minting is not open right now!");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 969");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
}
| 14,623,237 |
./full_match/1/0x28e12d5079D48BB0a8A20F6F2E6f6d4daA786120/sources/contracts/BlueSubs.sol | Return a community associated to a discord guild id discordGuildId The discord guild id to search for return community The community associated to the discord guild id/ | function getCommunity(string calldata discordGuildId) public view returns (Subscription memory community) {
return _communities[discordGuildId];
}
| 3,068,992 |
./full_match/4/0x432E51f07B842ed7692E1992b717523B6419990D/sources/contracts/Ownable.sol | Return an empty array | function mayanNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = mayanNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
| 12,336,435 |
./partial_match/1/0x29f81a819481044105a779480F3BA6b39eDc6c2D/sources/ERC20TOKEN.sol | @openzeppelin/contracts/token/ERC20/IERC20.sol | interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
Series A 2020 Digital Asset Management Interest
pragma solidity 0.5.17;
}
| 2,771,710 |
./full_match/1/0xE0fC587E1F56b5968a7d5DC3667bA1f385fddb38/sources/contracts/TermRepoCollateralManager.sol | borrower The address of the borrower closureRepoTokenAmounts An array specifying the amounts of Term Repo Tokens the liquidator proposes to cover borrower repo exposure in liquidation; an amount is required to be specified for each collateral token allow any liquidations if within margin minimum unencumber all collateral tokens owned by borrower if balance paid off | function batchLiquidationWithRepoToken(
address borrower,
uint256[] calldata closureRepoTokenAmounts
) external whileLiquidationsNotPaused {
bool allowFullLiquidation = _validateBatchLiquidationForFullLiquidation(
borrower,
msg.sender,
closureRepoTokenAmounts
);
uint256 totalClosureRepoTokenAmounts = 0;
uint256 closureValue;
uint256 collateralSeizureAmount;
uint256 collateralSeizureProtocolShare;
for (uint256 i = 0; i < closureRepoTokenAmounts.length; ++i) {
if (closureRepoTokenAmounts[i] == 0) {
continue;
}
if (closureRepoTokenAmounts[i] == type(uint256).max) {
revert InvalidParameters(
"closureRepoTokenAmounts cannot be uint max"
);
}
totalClosureRepoTokenAmounts += closureRepoTokenAmounts[i];
closureValue = termRepoServicer
.liquidatorCoverExposureWithRepoToken(
borrower,
msg.sender,
closureRepoTokenAmounts[i]
);
(
collateralSeizureAmount,
collateralSeizureProtocolShare
) = _collateralSeizureAmounts(closureValue, collateralTokens[i]);
_transferLiquidationCollateral(
borrower,
msg.sender,
collateralTokens[i],
closureRepoTokenAmounts[i],
collateralSeizureAmount,
collateralSeizureProtocolShare,
false
);
}
if (totalClosureRepoTokenAmounts == 0) {
revert ZeroLiquidationNotPermitted();
}
if (!allowFullLiquidation) {
if (!_withinNetExposureCapOnLiquidation(borrower)) {
revert ExceedsNetExposureCapOnLiquidation();
}
}
if (termRepoServicer.getBorrowerRepurchaseObligation(borrower) == 0) {
_unencumberRemainingBorrowerCollateralOnZeroObligation(borrower);
}
}
| 9,687,095 |
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
| this function is used to add nominee to a staking _stakingId - staking id _nomineeAddress - address of nominee to be added to staking _shares - amount of shares of the staking to the nominee shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it. , 'staking should active' , 'should not be nominee already' | function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
| 12,590,623 |
./full_match/5/0x191ceFa4a57F833988842636edcc34c68ea14ab3/sources/contracts/PepeSystems.sol | internal function checking if a connected wallet has delegations | function isDelegated() internal view returns (bool result) {
IDelegationRegistry.DelegationInfo[] memory delegationInfos;
delegationInfos = reg.getDelegationsByDelegate(msg.sender);
if (delegationInfos.length != 0) {
result = true;
}
}
| 1,857,756 |
./full_match/83/0xdb68eC6dFd21791cC9c1f4836b6499e2325461A7/sources/contracts/suErc20Delegator.sol | A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) token The address of the ERC-20 token to sweep/ | function sweepToken(EIP20NonStandardInterface token) external {
delegateToImplementation(abi.encodeWithSignature('sweepToken(address)', token));
}
| 9,556,341 |
./full_match/80001/0xc415006ac51e0D8adD1CC6fcAc74b25721512dc7/sources/contracts/ERC721A.sol | Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean. The nested ifs save around 20+ gas over a compound boolean condition. Clear approvals from the previous owner. This is equivalent to `delete _tokenApprovals[tokenId]`. Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow. Counter overflow is incredibly unrealistic as `tokenId` would have to be 2256. We can directly increment and decrement the balances. Updates: - `address` to the next owner. - `startTimestamp` to the timestamp of transfering. - `burned` to `false`. - `nextInitialized` to `true`. If the next slot may not have been initialized (i.e. `nextInitialized == false`) . If the next slot's address is zero and not burned (i.e. packed value is zero). If the next slot is within bounds. Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. Emit the `Transfer` event. | function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from)
_revert(TransferFromIncorrectOwner.selector);
(
uint256 approvedAddressSlot,
address approvedAddress
) = _getApprovedSlotAndAddress(tokenId);
if (
!_isSenderApprovedOrOwner(
approvedAddress,
from,
_msgSenderERC721A()
)
)
if (!isApprovedForAll(from, _msgSenderERC721A()))
_revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED |
_nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
| 836,010 |
./full_match/100/0xe37d4F73ef1C85dEf2174A394f17Ac65DD3cBB81/sources/contracts/core/connext/helpers/OZERC20.sol | See {IERC20-allowance}./ | function allowance(address _owner, address _spender) public view virtual override returns (uint256) {
return _allowances[_owner][_spender];
}
| 14,287,101 |
pragma solidity 0.4.25;
/// @title provides subject to role checking logic
contract IAccessPolicy {
////////////////////////
// Public functions
////////////////////////
/// @notice We don't make this function constant to allow for state-updating access controls such as rate limiting.
/// @dev checks if subject belongs to requested role for particular object
/// @param subject address to be checked against role, typically msg.sender
/// @param role identifier of required role
/// @param object contract instance context for role checking, typically contract requesting the check
/// @param verb additional data, in current AccessControll implementation msg.sig
/// @return if subject belongs to a role
function allowed(
address subject,
bytes32 role,
address object,
bytes4 verb
)
public
returns (bool);
}
/// @title enables access control in implementing contract
/// @dev see AccessControlled for implementation
contract IAccessControlled {
////////////////////////
// Events
////////////////////////
/// @dev must log on access policy change
event LogAccessPolicyChanged(
address controller,
IAccessPolicy oldPolicy,
IAccessPolicy newPolicy
);
////////////////////////
// Public functions
////////////////////////
/// @dev allows to change access control mechanism for this contract
/// this method must be itself access controlled, see AccessControlled implementation and notice below
/// @notice it is a huge issue for Solidity that modifiers are not part of function signature
/// then interfaces could be used for example to control access semantics
/// @param newPolicy new access policy to controll this contract
/// @param newAccessController address of ROLE_ACCESS_CONTROLLER of new policy that can set access to this contract
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public;
function accessPolicy()
public
constant
returns (IAccessPolicy);
}
contract StandardRoles {
////////////////////////
// Constants
////////////////////////
// @notice Soldity somehow doesn't evaluate this compile time
// @dev role which has rights to change permissions and set new policy in contract, keccak256("AccessController")
bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da;
}
/// @title Granular code execution permissions
/// @notice Intended to replace existing Ownable pattern with more granular permissions set to execute smart contract functions
/// for each function where 'only' modifier is applied, IAccessPolicy implementation is called to evaluate if msg.sender belongs to required role for contract being called.
/// Access evaluation specific belong to IAccessPolicy implementation, see RoleBasedAccessPolicy for details.
/// @dev Should be inherited by a contract requiring such permissions controll. IAccessPolicy must be provided in constructor. Access policy may be replaced to a different one
/// by msg.sender with ROLE_ACCESS_CONTROLLER role
contract AccessControlled is IAccessControlled, StandardRoles {
////////////////////////
// Mutable state
////////////////////////
IAccessPolicy private _accessPolicy;
////////////////////////
// Modifiers
////////////////////////
/// @dev limits function execution only to senders assigned to required 'role'
modifier only(bytes32 role) {
require(_accessPolicy.allowed(msg.sender, role, this, msg.sig));
_;
}
////////////////////////
// Constructor
////////////////////////
constructor(IAccessPolicy policy) internal {
require(address(policy) != 0x0);
_accessPolicy = policy;
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IAccessControlled
//
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public
only(ROLE_ACCESS_CONTROLLER)
{
// ROLE_ACCESS_CONTROLLER must be present
// under the new policy. This provides some
// protection against locking yourself out.
require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig));
// We can now safely set the new policy without foot shooting.
IAccessPolicy oldPolicy = _accessPolicy;
_accessPolicy = newPolicy;
// Log event
emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy);
}
function accessPolicy()
public
constant
returns (IAccessPolicy)
{
return _accessPolicy;
}
}
/// @title standard access roles of the Platform
/// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap
contract AccessRoles {
////////////////////////
// Constants
////////////////////////
// NOTE: All roles are set to the keccak256 hash of the
// CamelCased role name, i.e.
// ROLE_LOCKED_ACCOUNT_ADMIN = keccak256("LockedAccountAdmin")
// May issue (generate) Neumarks
bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c;
// May burn Neumarks it owns
bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f;
// May create new snapshots on Neumark
bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174;
// May enable/disable transfers on Neumark
bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19;
// may reclaim tokens/ether from contracts supporting IReclaimable interface
bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5;
// represents legally platform operator in case of forks and contracts with legal agreement attached. keccak256("PlatformOperatorRepresentative")
bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0;
// allows to deposit EUR-T and allow addresses to send and receive EUR-T. keccak256("EurtDepositManager")
bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7;
// allows to register identities and change associated claims keccak256("IdentityManager")
bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e;
// allows to replace controller on euro token and to destroy tokens without withdraw kecckak256("EurtLegalManager")
bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b;
// allows to change known interfaces in universe kecckak256("UniverseManager")
bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738;
// allows to exchange gas for EUR-T keccak("GasExchange")
bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969;
// allows to set token exchange rates keccak("TokenRateOracle")
bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585;
}
contract IEthereumForkArbiter {
////////////////////////
// Events
////////////////////////
event LogForkAnnounced(
string name,
string url,
uint256 blockNumber
);
event LogForkSigned(
uint256 blockNumber,
bytes32 blockHash
);
////////////////////////
// Public functions
////////////////////////
function nextForkName()
public
constant
returns (string);
function nextForkUrl()
public
constant
returns (string);
function nextForkBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockHash()
public
constant
returns (bytes32);
function lastSignedTimestamp()
public
constant
returns (uint256);
}
/**
* @title legally binding smart contract
* @dev General approach to paring legal and smart contracts:
* 1. All terms and agreement are between two parties: here between smart conctract legal representation and platform investor.
* 2. Parties are represented by public Ethereum addresses. Platform investor is and address that holds and controls funds and receives and controls Neumark token
* 3. Legal agreement has immutable part that corresponds to smart contract code and mutable part that may change for example due to changing regulations or other externalities that smart contract does not control.
* 4. There should be a provision in legal document that future changes in mutable part cannot change terms of immutable part.
* 5. Immutable part links to corresponding smart contract via its address.
* 6. Additional provision should be added if smart contract supports it
* a. Fork provision
* b. Bugfixing provision (unilateral code update mechanism)
* c. Migration provision (bilateral code update mechanism)
*
* Details on Agreement base class:
* 1. We bind smart contract to legal contract by storing uri (preferably ipfs or hash) of the legal contract in the smart contract. It is however crucial that such binding is done by smart contract legal representation so transaction establishing the link must be signed by respective wallet ('amendAgreement')
* 2. Mutable part of agreement may change. We should be able to amend the uri later. Previous amendments should not be lost and should be retrievable (`amendAgreement` and 'pastAgreement' functions).
* 3. It is up to deriving contract to decide where to put 'acceptAgreement' modifier. However situation where there is no cryptographic proof that given address was really acting in the transaction should be avoided, simplest example being 'to' address in `transfer` function of ERC20.
*
**/
contract IAgreement {
////////////////////////
// Events
////////////////////////
event LogAgreementAccepted(
address indexed accepter
);
event LogAgreementAmended(
address contractLegalRepresentative,
string agreementUri
);
/// @dev should have access restrictions so only contractLegalRepresentative may call
function amendAgreement(string agreementUri) public;
/// returns information on last amendment of the agreement
/// @dev MUST revert if no agreements were set
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
/// returns information on amendment with index
/// @dev MAY revert on non existing amendment, indexing starts from 0
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
/// returns the number of block at wchich `signatory` signed agreement
/// @dev MUST return 0 if not signed
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo);
/// returns number of amendments made by contractLegalRepresentative
function amendmentsCount()
public
constant
returns (uint256);
}
/**
* @title legally binding smart contract
* @dev read IAgreement for details
**/
contract Agreement is
IAgreement,
AccessControlled,
AccessRoles
{
////////////////////////
// Type declarations
////////////////////////
/// @notice agreement with signature of the platform operator representative
struct SignedAgreement {
address contractLegalRepresentative;
uint256 signedBlockTimestamp;
string agreementUri;
}
////////////////////////
// Immutable state
////////////////////////
IEthereumForkArbiter private ETHEREUM_FORK_ARBITER;
////////////////////////
// Mutable state
////////////////////////
// stores all amendments to the agreement, first amendment is the original
SignedAgreement[] private _amendments;
// stores block numbers of all addresses that signed the agreement (signatory => block number)
mapping(address => uint256) private _signatories;
////////////////////////
// Modifiers
////////////////////////
/// @notice logs that agreement was accepted by platform user
/// @dev intended to be added to functions that if used make 'accepter' origin to enter legally binding agreement
modifier acceptAgreement(address accepter) {
acceptAgreementInternal(accepter);
_;
}
modifier onlyLegalRepresentative(address legalRepresentative) {
require(mCanAmend(legalRepresentative));
_;
}
////////////////////////
// Constructor
////////////////////////
constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter)
AccessControlled(accessPolicy)
internal
{
require(forkArbiter != IEthereumForkArbiter(0x0));
ETHEREUM_FORK_ARBITER = forkArbiter;
}
////////////////////////
// Public functions
////////////////////////
function amendAgreement(string agreementUri)
public
onlyLegalRepresentative(msg.sender)
{
SignedAgreement memory amendment = SignedAgreement({
contractLegalRepresentative: msg.sender,
signedBlockTimestamp: block.timestamp,
agreementUri: agreementUri
});
_amendments.push(amendment);
emit LogAgreementAmended(msg.sender, agreementUri);
}
function ethereumForkArbiter()
public
constant
returns (IEthereumForkArbiter)
{
return ETHEREUM_FORK_ARBITER;
}
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
require(_amendments.length > 0);
uint256 last = _amendments.length - 1;
SignedAgreement storage amendment = _amendments[last];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
last
);
}
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
SignedAgreement storage amendment = _amendments[amendmentIndex];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
amendmentIndex
);
}
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo)
{
return _signatories[signatory];
}
function amendmentsCount()
public
constant
returns (uint256)
{
return _amendments.length;
}
////////////////////////
// Internal functions
////////////////////////
/// provides direct access to derived contract
function acceptAgreementInternal(address accepter)
internal
{
if(_signatories[accepter] == 0) {
require(_amendments.length > 0);
_signatories[accepter] = block.number;
emit LogAgreementAccepted(accepter);
}
}
//
// MAgreement Internal interface (todo: extract)
//
/// default amend permission goes to ROLE_PLATFORM_OPERATOR_REPRESENTATIVE
function mCanAmend(address legalRepresentative)
internal
returns (bool)
{
return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig);
}
}
/// @title describes layout of claims in 256bit records stored for identities
/// @dev intended to be derived by contracts requiring access to particular claims
contract IdentityRecord {
////////////////////////
// Types
////////////////////////
/// @dev here the idea is to have claims of size of uint256 and use this struct
/// to translate in and out of this struct. until we do not cross uint256 we
/// have binary compatibility
struct IdentityClaims {
bool isVerified; // 1 bit
bool isSophisticatedInvestor; // 1 bit
bool hasBankAccount; // 1 bit
bool accountFrozen; // 1 bit
// uint252 reserved
}
////////////////////////
// Internal functions
////////////////////////
/// translates uint256 to struct
function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) {
// for memory layout of struct, each field below word length occupies whole word
assembly {
mstore(claims, and(data, 0x1))
mstore(add(claims, 0x20), div(and(data, 0x2), 0x2))
mstore(add(claims, 0x40), div(and(data, 0x4), 0x4))
mstore(add(claims, 0x60), div(and(data, 0x8), 0x8))
}
}
}
/// @title interface storing and retrieve 256bit claims records for identity
/// actual format of record is decoupled from storage (except maximum size)
contract IIdentityRegistry {
////////////////////////
// Events
////////////////////////
/// provides information on setting claims
event LogSetClaims(
address indexed identity,
bytes32 oldClaims,
bytes32 newClaims
);
////////////////////////
// Public functions
////////////////////////
/// get claims for identity
function getClaims(address identity) public constant returns (bytes32);
/// set claims for identity
/// @dev odlClaims and newClaims used for optimistic locking. to override with newClaims
/// current claims must be oldClaims
function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public;
}
/// @title known interfaces (services) of the platform
/// "known interface" is a unique id of service provided by the platform and discovered via Universe contract
/// it does not refer to particular contract/interface ABI, particular service may be delivered via different implementations
/// however for a few contracts we commit platform to particular implementation (all ICBM Contracts, Universe itself etc.)
/// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap
contract KnownInterfaces {
////////////////////////
// Constants
////////////////////////
// NOTE: All interface are set to the keccak256 hash of the
// CamelCased interface or singleton name, i.e.
// KNOWN_INTERFACE_NEUMARK = keccak256("Neumark")
// EIP 165 + EIP 820 should be use instead but it seems they are far from finished
// also interface signature should be build automatically by solidity. otherwise it is a pure hassle
// neumark token interface and sigleton keccak256("Neumark")
bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd;
// ether token interface and singleton keccak256("EtherToken")
bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1;
// euro token interface and singleton keccak256("EuroToken")
bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b;
// identity registry interface and singleton keccak256("IIdentityRegistry")
bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073;
// currency rates oracle interface and singleton keccak256("ITokenExchangeRateOracle")
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e;
// fee disbursal interface and singleton keccak256("IFeeDisbursal")
bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8;
// platform portfolio holding equity tokens belonging to NEU holders keccak256("IPlatformPortfolio");
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0;
// token exchange interface and singleton keccak256("ITokenExchange")
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521;
// service exchanging euro token for gas ("IGasTokenExchange")
bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de;
// access policy interface and singleton keccak256("IAccessPolicy")
bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9;
// euro lock account (upgraded) keccak256("LockedAccount:Euro")
bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e;
// ether lock account (upgraded) keccak256("LockedAccount:Ether")
bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823;
// icbm euro lock account keccak256("ICBMLockedAccount:Euro")
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14;
// ether lock account (upgraded) keccak256("ICBMLockedAccount:Ether")
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006;
// ether token interface and singleton keccak256("ICBMEtherToken")
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9;
// euro token interface and singleton keccak256("ICBMEuroToken")
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72;
// ICBM commitment interface interface and singleton keccak256("ICBMCommitment")
bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef;
// ethereum fork arbiter interface and singleton keccak256("IEthereumForkArbiter")
bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c;
// Platform terms interface and singletong keccak256("PlatformTerms")
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8;
// for completness we define Universe service keccak256("Universe");
bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454;
// ETO commitment interface (collection) keccak256("ICommitment")
bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60;
// Equity Token Controller interface (collection) keccak256("IEquityTokenController")
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1;
// Equity Token interface (collection) keccak256("IEquityToken")
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb;
}
contract IsContract {
////////////////////////
// Internal functions
////////////////////////
function isContract(address addr)
internal
constant
returns (bool)
{
uint256 size;
// takes 700 gas
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract NeumarkIssuanceCurve {
////////////////////////
// Constants
////////////////////////
// maximum number of neumarks that may be created
uint256 private constant NEUMARK_CAP = 1500000000000000000000000000;
// initial neumark reward fraction (controls curve steepness)
uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000;
// stop issuing new Neumarks above this Euro value (as it goes quickly to zero)
uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000;
// approximate curve linearly above this Euro value
uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000;
uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871;
uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS;
uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS;
////////////////////////
// Public functions
////////////////////////
/// @notice returns additional amount of neumarks issued for euroUlps at totalEuroUlps
/// @param totalEuroUlps actual curve position from which neumarks will be issued
/// @param euroUlps amount against which neumarks will be issued
function incremental(uint256 totalEuroUlps, uint256 euroUlps)
public
pure
returns (uint256 neumarkUlps)
{
require(totalEuroUlps + euroUlps >= totalEuroUlps);
uint256 from = cumulative(totalEuroUlps);
uint256 to = cumulative(totalEuroUlps + euroUlps);
// as expansion is not monotonic for large totalEuroUlps, assert below may fail
// example: totalEuroUlps=1.999999999999999999999000000e+27 and euroUlps=50
assert(to >= from);
return to - from;
}
/// @notice returns amount of euro corresponding to burned neumarks
/// @param totalEuroUlps actual curve position from which neumarks will be burned
/// @param burnNeumarkUlps amount of neumarks to burn
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps);
// yes, this may overflow due to non monotonic inverse function
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
/// @notice returns amount of euro corresponding to burned neumarks
/// @param totalEuroUlps actual curve position from which neumarks will be burned
/// @param burnNeumarkUlps amount of neumarks to burn
/// @param minEurUlps euro amount to start inverse search from, inclusive
/// @param maxEurUlps euro amount to end inverse search to, inclusive
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps);
// yes, this may overflow due to non monotonic inverse function
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
/// @notice finds total amount of neumarks issued for given amount of Euro
/// @dev binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps
/// function below is not monotonic
function cumulative(uint256 euroUlps)
public
pure
returns(uint256 neumarkUlps)
{
// Return the cap if euroUlps is above the limit.
if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) {
return NEUMARK_CAP;
}
// use linear approximation above limit below
// binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps
if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) {
// (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS) is small so expression does not overflow
return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS;
}
// Approximate cap-cap·(1-1/D)^n using the Binomial expansion
// http://galileo.phys.virginia.edu/classes/152.mf1i.spring02/Exponential_Function.htm
// Function[imax, -CAP*Sum[(-IR*EUR/CAP)^i/Factorial[i], {i, imax}]]
// which may be simplified to
// Function[imax, -CAP*Sum[(EUR)^i/(Factorial[i]*(-d)^i), {i, 1, imax}]]
// where d = cap/initial_reward
uint256 d = 230769230769230769230769231; // NEUMARK_CAP / INITIAL_REWARD_FRACTION
uint256 term = NEUMARK_CAP;
uint256 sum = 0;
uint256 denom = d;
do assembly {
// We use assembler primarily to avoid the expensive
// divide-by-zero check solc inserts for the / operator.
term := div(mul(term, euroUlps), denom)
sum := add(sum, term)
denom := add(denom, d)
// sub next term as we have power of negative value in the binomial expansion
term := div(mul(term, euroUlps), denom)
sum := sub(sum, term)
denom := add(denom, d)
} while (term != 0);
return sum;
}
/// @notice find issuance curve inverse by binary search
/// @param neumarkUlps neumark amount to compute inverse for
/// @param minEurUlps minimum search range for the inverse, inclusive
/// @param maxEurUlps maxium search range for the inverse, inclusive
/// @dev in case of approximate search (no exact inverse) upper element of minimal search range is returned
/// @dev in case of many possible inverses, the lowest one will be used (if range permits)
/// @dev corresponds to a linear search that returns first euroUlp value that has cumulative() equal or greater than neumarkUlps
function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
require(maxEurUlps >= minEurUlps);
require(cumulative(minEurUlps) <= neumarkUlps);
require(cumulative(maxEurUlps) >= neumarkUlps);
uint256 min = minEurUlps;
uint256 max = maxEurUlps;
// Binary search
while (max > min) {
uint256 mid = (max + min) / 2;
uint256 val = cumulative(mid);
// exact solution should not be used, a late points of the curve when many euroUlps are needed to
// increase by one nmkUlp this will lead to "indeterministic" inverse values that depend on the initial min and max
// and further binary division -> you can land at any of the euro value that is mapped to the same nmk value
// with condition below removed, binary search will point to the lowest eur value possible which is good because it cannot be exploited even with 0 gas costs
/* if (val == neumarkUlps) {
return mid;
}*/
// NOTE: approximate search (no inverse) must return upper element of the final range
// last step of approximate search is always (min, min+1) so new mid is (2*min+1)/2 => min
// so new min = mid + 1 = max which was upper range. and that ends the search
// NOTE: when there are multiple inverses for the same neumarkUlps, the `max` will be dragged down
// by `max = mid` expression to the lowest eur value of inverse. works only for ranges that cover all points of multiple inverse
if (val < neumarkUlps) {
min = mid + 1;
} else {
max = mid;
}
}
// NOTE: It is possible that there is no inverse
// for example curve(0) = 0 and curve(1) = 6, so
// there is no value y such that curve(y) = 5.
// When there is no inverse, we must return upper element of last search range.
// This has the effect of reversing the curve less when
// burning Neumarks. This ensures that Neumarks can always
// be burned. It also ensure that the total supply of Neumarks
// remains below the cap.
return max;
}
function neumarkCap()
public
pure
returns (uint256)
{
return NEUMARK_CAP;
}
function initialRewardFraction()
public
pure
returns (uint256)
{
return INITIAL_REWARD_FRACTION;
}
}
contract IBasicToken {
////////////////////////
// Events
////////////////////////
event Transfer(
address indexed from,
address indexed to,
uint256 amount
);
////////////////////////
// Public functions
////////////////////////
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply()
public
constant
returns (uint256);
/// @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);
/// @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);
}
/// @title allows deriving contract to recover any token or ether that it has balance of
/// @notice note that this opens your contracts to claims from various people saying they lost tokens and they want them back
/// be ready to handle such claims
/// @dev use with care!
/// 1. ROLE_RECLAIMER is allowed to claim tokens, it's not returning tokens to original owner
/// 2. in derived contract that holds any token by design you must override `reclaim` and block such possibility.
/// see ICBMLockedAccount as an example
contract Reclaimable is AccessControlled, AccessRoles {
////////////////////////
// Constants
////////////////////////
IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0);
////////////////////////
// Public functions
////////////////////////
function reclaim(IBasicToken token)
public
only(ROLE_RECLAIMER)
{
address reclaimer = msg.sender;
if(token == RECLAIM_ETHER) {
reclaimer.transfer(address(this).balance);
} else {
uint256 balance = token.balanceOf(this);
require(token.transfer(reclaimer, balance));
}
}
}
/// @title advances snapshot id on demand
/// @dev see Snapshot folder for implementation examples ie. DailyAndSnapshotable contract
contract ISnapshotable {
////////////////////////
// Events
////////////////////////
/// @dev should log each new snapshot id created, including snapshots created automatically via MSnapshotPolicy
event LogSnapshotCreated(uint256 snapshotId);
////////////////////////
// Public functions
////////////////////////
/// always creates new snapshot id which gets returned
/// however, there is no guarantee that any snapshot will be created with this id, this depends on the implementation of MSnaphotPolicy
function createSnapshot()
public
returns (uint256);
/// upper bound of series snapshotIds for which there's a value
function currentSnapshotId()
public
constant
returns (uint256);
}
/// @title Abstracts snapshot id creation logics
/// @dev Mixin (internal interface) of the snapshot policy which abstracts snapshot id creation logics from Snapshot contract
/// @dev to be implemented and such implementation should be mixed with Snapshot-derived contract, see EveryBlock for simplest example of implementation and StandardSnapshotToken
contract MSnapshotPolicy {
////////////////////////
// Internal functions
////////////////////////
// The snapshot Ids need to be strictly increasing.
// Whenever the snaspshot id changes, a new snapshot will be created.
// As long as the same snapshot id is being returned, last snapshot will be updated as this indicates that snapshot id didn't change
//
// Values passed to `hasValueAt` and `valuteAt` are required
// to be less or equal to `mCurrentSnapshotId()`.
function mAdvanceSnapshotId()
internal
returns (uint256);
// this is a version of mAdvanceSnapshotId that does not modify state but MUST return the same value
// it is required to implement ITokenSnapshots interface cleanly
function mCurrentSnapshotId()
internal
constant
returns (uint256);
}
/// @title creates new snapshot id on each day boundary
/// @dev snapshot id is unix timestamp of current day boundary
contract Daily is MSnapshotPolicy {
////////////////////////
// Constants
////////////////////////
// Floor[2**128 / 1 days]
uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391;
////////////////////////
// Constructor
////////////////////////
/// @param start snapshotId from which to start generating values, used to prevent cloning from incompatible schemes
/// @dev start must be for the same day or 0, required for token cloning
constructor(uint256 start) internal {
// 0 is invalid value as we are past unix epoch
if (start > 0) {
uint256 base = dayBase(uint128(block.timestamp));
// must be within current day base
require(start >= base);
// dayBase + 2**128 will not overflow as it is based on block.timestamp
require(start < base + 2**128);
}
}
////////////////////////
// Public functions
////////////////////////
function snapshotAt(uint256 timestamp)
public
constant
returns (uint256)
{
require(timestamp < MAX_TIMESTAMP);
return dayBase(uint128(timestamp));
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MSnapshotPolicy
//
function mAdvanceSnapshotId()
internal
returns (uint256)
{
return mCurrentSnapshotId();
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
// disregard overflows on block.timestamp, see MAX_TIMESTAMP
return dayBase(uint128(block.timestamp));
}
function dayBase(uint128 timestamp)
internal
pure
returns (uint256)
{
// Round down to the start of the day (00:00 UTC) and place in higher 128bits
return 2**128 * (uint256(timestamp) / 1 days);
}
}
/// @title creates snapshot id on each day boundary and allows to create additional snapshots within a given day
/// @dev snapshots are encoded in single uint256, where high 128 bits represents a day number (from unix epoch) and low 128 bits represents additional snapshots within given day create via ISnapshotable
contract DailyAndSnapshotable is
Daily,
ISnapshotable
{
////////////////////////
// Mutable state
////////////////////////
uint256 private _currentSnapshotId;
////////////////////////
// Constructor
////////////////////////
/// @param start snapshotId from which to start generating values
/// @dev start must be for the same day or 0, required for token cloning
constructor(uint256 start)
internal
Daily(start)
{
if (start > 0) {
_currentSnapshotId = start;
}
}
////////////////////////
// Public functions
////////////////////////
//
// Implements ISnapshotable
//
function createSnapshot()
public
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
// New day has started, create snapshot for midnight
_currentSnapshotId = base;
} else {
// within single day, increase counter (assume 2**128 will not be crossed)
_currentSnapshotId += 1;
}
// Log and return
emit LogSnapshotCreated(_currentSnapshotId);
return _currentSnapshotId;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MSnapshotPolicy
//
function mAdvanceSnapshotId()
internal
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
// New day has started
if (base > _currentSnapshotId) {
_currentSnapshotId = base;
emit LogSnapshotCreated(base);
}
return _currentSnapshotId;
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
return base > _currentSnapshotId ? base : _currentSnapshotId;
}
}
contract ITokenMetadata {
////////////////////////
// Public functions
////////////////////////
function symbol()
public
constant
returns (string);
function name()
public
constant
returns (string);
function decimals()
public
constant
returns (uint8);
}
/// @title adds token metadata to token contract
/// @dev see Neumark for example implementation
contract TokenMetadata is ITokenMetadata {
////////////////////////
// Immutable state
////////////////////////
// The Token's name: e.g. DigixDAO Tokens
string private NAME;
// An identifier: e.g. REP
string private SYMBOL;
// Number of decimals of the smallest unit
uint8 private DECIMALS;
// An arbitrary versioning scheme
string private VERSION;
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to set metadata
/// @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 version Token version ie. when cloning is used
constructor(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
{
NAME = tokenName; // Set the name
SYMBOL = tokenSymbol; // Set the symbol
DECIMALS = decimalUnits; // Set the decimals
VERSION = version;
}
////////////////////////
// Public functions
////////////////////////
function name()
public
constant
returns (string)
{
return NAME;
}
function symbol()
public
constant
returns (string)
{
return SYMBOL;
}
function decimals()
public
constant
returns (uint8)
{
return DECIMALS;
}
function version()
public
constant
returns (string)
{
return VERSION;
}
}
contract IERC20Allowance {
////////////////////////
// Events
////////////////////////
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
////////////////////////
// Public functions
////////////////////////
/// @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);
/// @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);
/// @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);
}
contract IERC20Token is IBasicToken, IERC20Allowance {
}
/// @title controls spending approvals
/// @dev TokenAllowance observes this interface, Neumark contract implements it
contract MTokenAllowanceController {
////////////////////////
// Internal functions
////////////////////////
/// @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 mOnApprove(
address owner,
address spender,
uint256 amount
)
internal
returns (bool allow);
/// @notice Allows to override allowance approved by the owner
/// Primary role is to enable forced transfers, do not override if you do not like it
/// Following behavior is expected in the observer
/// approve() - should revert if mAllowanceOverride() > 0
/// allowance() - should return mAllowanceOverride() if set
/// transferFrom() - should override allowance if mAllowanceOverride() > 0
/// @param owner An address giving allowance to spender
/// @param spender An address getting a right to transfer allowance amount from the owner
/// @return current allowance amount
function mAllowanceOverride(
address owner,
address spender
)
internal
constant
returns (uint256 allowance);
}
/// @title controls token transfers
/// @dev BasicSnapshotToken observes this interface, Neumark contract implements it
contract MTokenTransferController {
////////////////////////
// Internal functions
////////////////////////
/// @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 mOnTransfer(
address from,
address to,
uint256 amount
)
internal
returns (bool allow);
}
/// @title controls approvals and transfers
/// @dev The token controller contract must implement these functions, see Neumark as example
/// @dev please note that controller may be a separate contract that is called from mOnTransfer and mOnApprove functions
contract MTokenController is MTokenTransferController, MTokenAllowanceController {
}
/// @title internal token transfer function
/// @dev see BasicSnapshotToken for implementation
contract MTokenTransfer {
////////////////////////
// Internal functions
////////////////////////
/// @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
/// @dev reverts if transfer was not successful
function mTransfer(
address from,
address to,
uint256 amount
)
internal;
}
contract IERC677Callback {
////////////////////////
// Public functions
////////////////////////
// NOTE: This call can be initiated by anyone. You need to make sure that
// it is send by the token (`require(msg.sender == token)`) or make sure
// amount is valid (`require(token.allowance(this) >= amount)`).
function receiveApproval(
address from,
uint256 amount,
address token, // IERC667Token
bytes data
)
public
returns (bool success);
}
contract IERC677Allowance is IERC20Allowance {
////////////////////////
// Public functions
////////////////////////
/// @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(address spender, uint256 amount, bytes extraData)
public
returns (bool success);
}
contract IERC677Token is IERC20Token, IERC677Allowance {
}
/// @title token spending approval and transfer
/// @dev implements token approval and transfers and exposes relevant part of ERC20 and ERC677 approveAndCall
/// may be mixed in with any basic token (implementing mTransfer) like BasicSnapshotToken or MintableSnapshotToken to add approval mechanism
/// observes MTokenAllowanceController interface
/// observes MTokenTransfer
contract TokenAllowance is
MTokenTransfer,
MTokenAllowanceController,
IERC20Allowance,
IERC677Token
{
////////////////////////
// Mutable state
////////////////////////
// `allowed` tracks rights to spends others tokens as per ERC20
// owner => spender => amount
mapping (address => mapping (address => uint256)) private _allowed;
////////////////////////
// Constructor
////////////////////////
constructor()
internal
{
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IERC20Token
//
/// @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)
{
uint256 override = mAllowanceOverride(owner, spender);
if (override > 0) {
return override;
}
return _allowed[owner][spender];
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// where allowance per spender must be 0 to allow change of such allowance
/// @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 or reverts, False is never returned
function approve(address spender, uint256 amount)
public
returns (bool success)
{
// Alerts the token controller of the approve function call
require(mOnApprove(msg.sender, spender, amount));
// 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) && mAllowanceOverride(msg.sender, spender) == 0);
_allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param from The address holding the tokens being transferred
/// @param to The address of the recipient
/// @param amount The amount of tokens to be transferred
/// @return True if the transfer was successful, reverts in any other case
function transferFrom(address from, address to, uint256 amount)
public
returns (bool success)
{
uint256 allowed = mAllowanceOverride(from, msg.sender);
if (allowed == 0) {
// The standard ERC 20 transferFrom functionality
allowed = _allowed[from][msg.sender];
// yes this will underflow but then we'll revert. will cost gas however so don't underflow
_allowed[from][msg.sender] -= amount;
}
require(allowed >= amount);
mTransfer(from, to, amount);
return true;
}
//
// Implements IERC677Token
//
/// @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 or reverts, False is never returned
function approveAndCall(
address spender,
uint256 amount,
bytes extraData
)
public
returns (bool success)
{
require(approve(spender, amount));
success = IERC677Callback(spender).receiveApproval(
msg.sender,
amount,
this,
extraData
);
require(success);
return true;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements default MTokenAllowanceController
//
// no override in default implementation
function mAllowanceOverride(
address /*owner*/,
address /*spender*/
)
internal
constant
returns (uint256)
{
return 0;
}
}
/// @title Reads and writes snapshots
/// @dev Manages reading and writing a series of values, where each value has assigned a snapshot id for access to historical data
/// @dev may be added to any contract to provide snapshotting mechanism. should be mixed in with any of MSnapshotPolicy implementations to customize snapshot creation mechanics
/// observes MSnapshotPolicy
/// based on MiniMe token
contract Snapshot is MSnapshotPolicy {
////////////////////////
// Types
////////////////////////
/// @dev `Values` is the structure that attaches a snapshot id to a
/// given value, the snapshot id attached is the one that last changed the
/// value
struct Values {
// `snapshotId` is the snapshot id that the value was generated at
uint256 snapshotId;
// `value` at a specific snapshot id
uint256 value;
}
////////////////////////
// Internal functions
////////////////////////
function hasValue(
Values[] storage values
)
internal
constant
returns (bool)
{
return values.length > 0;
}
/// @dev makes sure that 'snapshotId' between current snapshot id (mCurrentSnapshotId) and first snapshot id. this guarantees that getValueAt returns value from one of the snapshots.
function hasValueAt(
Values[] storage values,
uint256 snapshotId
)
internal
constant
returns (bool)
{
require(snapshotId <= mCurrentSnapshotId());
return values.length > 0 && values[0].snapshotId <= snapshotId;
}
/// gets last value in the series
function getValue(
Values[] storage values,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
if (values.length == 0) {
return defaultValue;
} else {
uint256 last = values.length - 1;
return values[last].value;
}
}
/// @dev `getValueAt` retrieves value at a given snapshot id
/// @param values The series of values being queried
/// @param snapshotId Snapshot id to retrieve the value at
/// @return Value in series being queried
function getValueAt(
Values[] storage values,
uint256 snapshotId,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
require(snapshotId <= mCurrentSnapshotId());
// Empty value
if (values.length == 0) {
return defaultValue;
}
// Shortcut for the out of bounds snapshots
uint256 last = values.length - 1;
uint256 lastSnapshot = values[last].snapshotId;
if (snapshotId >= lastSnapshot) {
return values[last].value;
}
uint256 firstSnapshot = values[0].snapshotId;
if (snapshotId < firstSnapshot) {
return defaultValue;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = last;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
// must always return lower indice for approximate searches
if (values[mid].snapshotId <= snapshotId) {
min = mid;
} else {
max = mid - 1;
}
}
return values[min].value;
}
/// @dev `setValue` used to update sequence at next snapshot
/// @param values The sequence being updated
/// @param value The new last value of sequence
function setValue(
Values[] storage values,
uint256 value
)
internal
{
// TODO: simplify or break into smaller functions
uint256 currentSnapshotId = mAdvanceSnapshotId();
// Always create a new entry if there currently is no value
bool empty = values.length == 0;
if (empty) {
// Create a new entry
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
return;
}
uint256 last = values.length - 1;
bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId;
if (hasNewSnapshot) {
// Do nothing if the value was not modified
bool unmodified = values[last].value == value;
if (unmodified) {
return;
}
// Create new entry
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
} else {
// We are updating the currentSnapshotId
bool previousUnmodified = last > 0 && values[last - 1].value == value;
if (previousUnmodified) {
// Remove current snapshot if current value was set to previous value
delete values[last];
values.length--;
return;
}
// Overwrite next snapshot entry
values[last].value = value;
}
}
}
/// @title access to snapshots of a token
/// @notice allows to implement complex token holder rights like revenue disbursal or voting
/// @notice snapshots are series of values with assigned ids. ids increase strictly. particular id mechanism is not assumed
contract ITokenSnapshots {
////////////////////////
// Public functions
////////////////////////
/// @notice Total amount of tokens at a specific `snapshotId`.
/// @param snapshotId of snapshot at which totalSupply is queried
/// @return The total amount of tokens at `snapshotId`
/// @dev reverts on snapshotIds greater than currentSnapshotId()
/// @dev returns 0 for snapshotIds less than snapshotId of first value
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256);
/// @dev Queries the balance of `owner` at a specific `snapshotId`
/// @param owner The address from which the balance will be retrieved
/// @param snapshotId of snapshot at which the balance is queried
/// @return The balance at `snapshotId`
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256);
/// @notice upper bound of series of snapshotIds for which there's a value in series
/// @return snapshotId
function currentSnapshotId()
public
constant
returns (uint256);
}
/// @title represents link between cloned and parent token
/// @dev when token is clone from other token, initial balances of the cloned token
/// correspond to balances of parent token at the moment of parent snapshot id specified
/// @notice please note that other tokens beside snapshot token may be cloned
contract IClonedTokenParent is ITokenSnapshots {
////////////////////////
// Public functions
////////////////////////
/// @return address of parent token, address(0) if root
/// @dev parent token does not need to clonable, nor snapshottable, just a normal token
function parentToken()
public
constant
returns(IClonedTokenParent parent);
/// @return snapshot at wchich initial token distribution was taken
function parentSnapshotId()
public
constant
returns(uint256 snapshotId);
}
/// @title token with snapshots and transfer functionality
/// @dev observes MTokenTransferController interface
/// observes ISnapshotToken interface
/// implementes MTokenTransfer interface
contract BasicSnapshotToken is
MTokenTransfer,
MTokenTransferController,
IClonedTokenParent,
IBasicToken,
Snapshot
{
////////////////////////
// Immutable state
////////////////////////
// `PARENT_TOKEN` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
IClonedTokenParent private PARENT_TOKEN;
// `PARENT_SNAPSHOT_ID` is the snapshot id from the Parent Token that was
// used to determine the initial distribution of the cloned token
uint256 private PARENT_SNAPSHOT_ID;
////////////////////////
// Mutable state
////////////////////////
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the snapshot id that the change
// occurred is also included in the map
mapping (address => Values[]) internal _balances;
// Tracks the history of the `totalSupply` of the token
Values[] internal _totalSupplyValues;
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create snapshot token
/// @param parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param parentSnapshotId at which snapshot id clone was created, set to 0 to clone at upper bound
/// @dev please not that as long as cloned token does not overwrite value at current snapshot id, it will refer
/// to parent token at which this snapshot still may change until snapshot id increases. for that time tokens are coupled
/// this is prevented by parentSnapshotId value of parentToken.currentSnapshotId() - 1 being the maxiumum
/// see SnapshotToken.js test to learn consequences coupling has.
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
Snapshot()
internal
{
PARENT_TOKEN = parentToken;
if (parentToken == address(0)) {
require(parentSnapshotId == 0);
} else {
if (parentSnapshotId == 0) {
require(parentToken.currentSnapshotId() > 0);
PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1;
} else {
PARENT_SNAPSHOT_ID = parentSnapshotId;
}
}
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IBasicToken
//
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply()
public
constant
returns (uint256)
{
return totalSupplyAtInternal(mCurrentSnapshotId());
}
/// @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 balanceOfAtInternal(owner, mCurrentSnapshotId());
}
/// @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 True if the transfer was successful, reverts in any other case
function transfer(address to, uint256 amount)
public
returns (bool success)
{
mTransfer(msg.sender, to, amount);
return true;
}
//
// Implements ITokenSnapshots
//
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256)
{
return totalSupplyAtInternal(snapshotId);
}
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256)
{
return balanceOfAtInternal(owner, snapshotId);
}
function currentSnapshotId()
public
constant
returns (uint256)
{
return mCurrentSnapshotId();
}
//
// Implements IClonedTokenParent
//
function parentToken()
public
constant
returns(IClonedTokenParent parent)
{
return PARENT_TOKEN;
}
/// @return snapshot at wchich initial token distribution was taken
function parentSnapshotId()
public
constant
returns(uint256 snapshotId)
{
return PARENT_SNAPSHOT_ID;
}
//
// Other public functions
//
/// @notice gets all token balances of 'owner'
/// @dev intended to be called via eth_call where gas limit is not an issue
function allBalancesOf(address owner)
external
constant
returns (uint256[2][])
{
/* very nice and working implementation below,
// copy to memory
Values[] memory values = _balances[owner];
do assembly {
// in memory structs have simple layout where every item occupies uint256
balances := values
} while (false);*/
Values[] storage values = _balances[owner];
uint256[2][] memory balances = new uint256[2][](values.length);
for(uint256 ii = 0; ii < values.length; ++ii) {
balances[ii] = [values[ii].snapshotId, values[ii].value];
}
return balances;
}
////////////////////////
// Internal functions
////////////////////////
function totalSupplyAtInternal(uint256 snapshotId)
internal
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
// If there is a value, return it, reverts if value is in the future
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
// Try parent contract at or before the fork
if (address(PARENT_TOKEN) != 0) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId);
}
// Default to an empty balance
return 0;
}
// get balance at snapshot if with continuation in parent token
function balanceOfAtInternal(address owner, uint256 snapshotId)
internal
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
// If there is a value, return it, reverts if value is in the future
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
// Try parent contract at or before the fork
if (PARENT_TOKEN != address(0)) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId);
}
// Default to an empty balance
return 0;
}
//
// Implements MTokenTransfer
//
/// @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, reverts in any other case
function mTransfer(
address from,
address to,
uint256 amount
)
internal
{
// never send to address 0
require(to != address(0));
// block transfers in clone that points to future/current snapshots of parent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
// Alerts the token controller of the transfer
require(mOnTransfer(from, to, amount));
// If the amount being transfered is more than the balance of the
// account the transfer reverts
uint256 previousBalanceFrom = balanceOf(from);
require(previousBalanceFrom >= amount);
// First update the balance array with the new value for the address
// sending the tokens
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_balances[from], newBalanceFrom);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOf(to);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_balances[to], newBalanceTo);
// An event to make the transfer easy to find on the blockchain
emit Transfer(from, to, amount);
}
}
/// @title token generation and destruction
/// @dev internal interface providing token generation and destruction, see MintableSnapshotToken for implementation
contract MTokenMint {
////////////////////////
// Internal functions
////////////////////////
/// @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
/// @dev reverts if tokens could not be generated
function mGenerateTokens(address owner, uint256 amount)
internal;
/// @notice Burns `amount` tokens from `owner`
/// @param owner The address that will lose the tokens
/// @param amount The quantity of tokens to burn
/// @dev reverts if tokens could not be destroyed
function mDestroyTokens(address owner, uint256 amount)
internal;
}
/// @title basic snapshot token with facitilites to generate and destroy tokens
/// @dev implementes MTokenMint, does not expose any public functions that create/destroy tokens
contract MintableSnapshotToken is
BasicSnapshotToken,
MTokenMint
{
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create a MintableSnapshotToken
/// @param parentToken Address of the parent token, set to 0x0 if it is a
/// new token
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
BasicSnapshotToken(parentToken, parentSnapshotId)
internal
{}
/// @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
function mGenerateTokens(address owner, uint256 amount)
internal
{
// never create for address 0
require(owner != address(0));
// block changes in clone that points to future/current snapshots of patent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
require(newTotalSupply >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
emit Transfer(0, owner, amount);
}
/// @notice Burns `amount` tokens from `owner`
/// @param owner The address that will lose the tokens
/// @param amount The quantity of tokens to burn
function mDestroyTokens(address owner, uint256 amount)
internal
{
// block changes in clone that points to future/current snapshots of patent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= amount);
uint256 previousBalanceFrom = balanceOf(owner);
require(previousBalanceFrom >= amount);
uint256 newTotalSupply = curTotalSupply - amount;
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceFrom);
emit Transfer(owner, 0, amount);
}
}
/*
Copyright 2016, Jordi Baylina
Copyright 2017, Remco Bloemen, Marcin Rudolf
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 StandardSnapshotToken Contract
/// @author Jordi Baylina, Remco Bloemen, Marcin Rudolf
/// @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.
/// @dev Various contracts are composed to provide required functionality of this token, different compositions are possible
/// MintableSnapshotToken provides transfer, miniting and snapshotting functions
/// TokenAllowance provides approve/transferFrom functions
/// TokenMetadata adds name, symbol and other token metadata
/// @dev This token is still abstract, Snapshot, BasicSnapshotToken and TokenAllowance observe interfaces that must be implemented
/// MSnapshotPolicy - particular snapshot id creation mechanism
/// MTokenController - controlls approvals and transfers
/// see Neumark as an example
/// @dev implements ERC223 token transfer
contract StandardSnapshotToken is
MintableSnapshotToken,
TokenAllowance
{
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create a MiniMeToken
/// 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
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
MintableSnapshotToken(parentToken, parentSnapshotId)
TokenAllowance()
internal
{}
}
/// @title old ERC223 callback function
/// @dev as used in Neumark and ICBMEtherToken
contract IERC223LegacyCallback {
////////////////////////
// Public functions
////////////////////////
function onTokenTransfer(address from, uint256 amount, bytes data)
public;
}
contract IERC223Token is IERC20Token, ITokenMetadata {
/// @dev Departure: We do not log data, it has no advantage over a standard
/// log event. By sticking to the standard log event we
/// stay compatible with constracts that expect and ERC20 token.
// event Transfer(
// address indexed from,
// address indexed to,
// uint256 amount,
// bytes data);
/// @dev Departure: We do not use the callback on regular transfer calls to
/// stay compatible with constracts that expect and ERC20 token.
// function transfer(address to, uint256 amount)
// public
// returns (bool);
////////////////////////
// Public functions
////////////////////////
function transfer(address to, uint256 amount, bytes data)
public
returns (bool);
}
contract Neumark is
AccessControlled,
AccessRoles,
Agreement,
DailyAndSnapshotable,
StandardSnapshotToken,
TokenMetadata,
IERC223Token,
NeumarkIssuanceCurve,
Reclaimable,
IsContract
{
////////////////////////
// Constants
////////////////////////
string private constant TOKEN_NAME = "Neumark";
uint8 private constant TOKEN_DECIMALS = 18;
string private constant TOKEN_SYMBOL = "NEU";
string private constant VERSION = "NMK_1.0";
////////////////////////
// Mutable state
////////////////////////
// disable transfers when Neumark is created
bool private _transferEnabled = false;
// at which point on curve new Neumarks will be created, see NeumarkIssuanceCurve contract
// do not use to get total invested funds. see burn(). this is just a cache for expensive inverse function
uint256 private _totalEurUlps;
////////////////////////
// Events
////////////////////////
event LogNeumarksIssued(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
event LogNeumarksBurned(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
////////////////////////
// Constructor
////////////////////////
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
AccessRoles()
Agreement(accessPolicy, forkArbiter)
StandardSnapshotToken(
IClonedTokenParent(0x0),
0
)
TokenMetadata(
TOKEN_NAME,
TOKEN_DECIMALS,
TOKEN_SYMBOL,
VERSION
)
DailyAndSnapshotable(0)
NeumarkIssuanceCurve()
Reclaimable()
public
{}
////////////////////////
// Public functions
////////////////////////
/// @notice issues new Neumarks to msg.sender with reward at current curve position
/// moves curve position by euroUlps
/// callable only by ROLE_NEUMARK_ISSUER
function issueForEuro(uint256 euroUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(msg.sender)
returns (uint256)
{
require(_totalEurUlps + euroUlps >= _totalEurUlps);
uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps);
_totalEurUlps += euroUlps;
mGenerateTokens(msg.sender, neumarkUlps);
emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps);
return neumarkUlps;
}
/// @notice used by ROLE_NEUMARK_ISSUER to transer newly issued neumarks
/// typically to the investor and platform operator
function distribute(address to, uint256 neumarkUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(to)
{
mTransfer(msg.sender, to, neumarkUlps);
}
/// @notice msg.sender can burn their Neumarks, curve is rolled back using inverse
/// curve. as a result cost of Neumark gets lower (reward is higher)
function burn(uint256 neumarkUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, 0, _totalEurUlps);
}
/// @notice executes as function above but allows to provide search range for low gas burning
function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, minEurUlps, maxEurUlps);
}
function enableTransfer(bool enabled)
public
only(ROLE_TRANSFER_ADMIN)
{
_transferEnabled = enabled;
}
function createSnapshot()
public
only(ROLE_SNAPSHOT_CREATOR)
returns (uint256)
{
return DailyAndSnapshotable.createSnapshot();
}
function transferEnabled()
public
constant
returns (bool)
{
return _transferEnabled;
}
function totalEuroUlps()
public
constant
returns (uint256)
{
return _totalEurUlps;
}
function incremental(uint256 euroUlps)
public
constant
returns (uint256 neumarkUlps)
{
return incremental(_totalEurUlps, euroUlps);
}
//
// Implements IERC223Token with IERC223Callback (onTokenTransfer) callback
//
// old implementation of ERC223 that was actual when ICBM was deployed
// as Neumark is already deployed this function keeps old behavior for testing
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
// it is necessary to point out implementation to be called
BasicSnapshotToken.mTransfer(msg.sender, to, amount);
// Notify the receiving contract.
if (isContract(to)) {
IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data);
}
return true;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MTokenController
//
function mOnTransfer(
address from,
address, // to
uint256 // amount
)
internal
acceptAgreement(from)
returns (bool allow)
{
// must have transfer enabled or msg.sender is Neumark issuer
return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig);
}
function mOnApprove(
address owner,
address, // spender,
uint256 // amount
)
internal
acceptAgreement(owner)
returns (bool allow)
{
return true;
}
////////////////////////
// Private functions
////////////////////////
function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
private
{
uint256 prevEuroUlps = _totalEurUlps;
// burn first in the token to make sure balance/totalSupply is not crossed
mDestroyTokens(msg.sender, burnNeumarkUlps);
_totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps);
// actually may overflow on non-monotonic inverse
assert(prevEuroUlps >= _totalEurUlps);
uint256 euroUlps = prevEuroUlps - _totalEurUlps;
emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps);
}
}
/// @title uniquely identifies deployable (non-abstract) platform contract
/// @notice cheap way of assigning implementations to knownInterfaces which represent system services
/// unfortunatelly ERC165 does not include full public interface (ABI) and does not provide way to list implemented interfaces
/// EIP820 still in the making
/// @dev ids are generated as follows keccak256("neufund-platform:<contract name>")
/// ids roughly correspond to ABIs
contract IContractId {
/// @param id defined as above
/// @param version implementation version
function contractId() public pure returns (bytes32 id, uint256 version);
}
/// @title current ERC223 fallback function
/// @dev to be used in all future token contract
/// @dev NEU and ICBMEtherToken (obsolete) are the only contracts that still uses IERC223LegacyCallback
contract IERC223Callback {
////////////////////////
// Public functions
////////////////////////
function tokenFallback(address from, uint256 amount, bytes data)
public;
}
/// @title disburse payment token amount to snapshot token holders
/// @dev payment token received via ERC223 Transfer
contract IFeeDisbursal is IERC223Callback {
// TODO: declare interface
}
/// @title disburse payment token amount to snapshot token holders
/// @dev payment token received via ERC223 Transfer
contract IPlatformPortfolio is IERC223Callback {
// TODO: declare interface
}
contract ITokenExchangeRateOracle {
/// @notice provides actual price of 'numeratorToken' in 'denominatorToken'
/// returns timestamp at which price was obtained in oracle
function getExchangeRate(address numeratorToken, address denominatorToken)
public
constant
returns (uint256 rateFraction, uint256 timestamp);
/// @notice allows to retreive multiple exchange rates in once call
function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens)
public
constant
returns (uint256[] rateFractions, uint256[] timestamps);
}
/// @title root of trust and singletons + known interface registry
/// provides a root which holds all interfaces platform trust, this includes
/// singletons - for which accessors are provided
/// collections of known instances of interfaces
/// @dev interfaces are identified by bytes4, see KnownInterfaces.sol
contract Universe is
Agreement,
IContractId,
KnownInterfaces
{
////////////////////////
// Events
////////////////////////
/// raised on any change of singleton instance
/// @dev for convenience we provide previous instance of singleton in replacedInstance
event LogSetSingleton(
bytes4 interfaceId,
address instance,
address replacedInstance
);
/// raised on add/remove interface instance in collection
event LogSetCollectionInterface(
bytes4 interfaceId,
address instance,
bool isSet
);
////////////////////////
// Mutable state
////////////////////////
// mapping of known contracts to addresses of singletons
mapping(bytes4 => address) private _singletons;
// mapping of known interfaces to collections of contracts
mapping(bytes4 =>
mapping(address => bool)) private _collections; // solium-disable-line indentation
// known instances
mapping(address => bytes4[]) private _instances;
////////////////////////
// Constructor
////////////////////////
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
Agreement(accessPolicy, forkArbiter)
public
{
setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy);
setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter);
}
////////////////////////
// Public methods
////////////////////////
/// get singleton instance for 'interfaceId'
function getSingleton(bytes4 interfaceId)
public
constant
returns (address)
{
return _singletons[interfaceId];
}
function getManySingletons(bytes4[] interfaceIds)
public
constant
returns (address[])
{
address[] memory addresses = new address[](interfaceIds.length);
uint256 idx;
while(idx < interfaceIds.length) {
addresses[idx] = _singletons[interfaceIds[idx]];
idx += 1;
}
return addresses;
}
/// checks of 'instance' is instance of interface 'interfaceId'
function isSingleton(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _singletons[interfaceId] == instance;
}
/// checks if 'instance' is one of instances of 'interfaceId'
function isInterfaceCollectionInstance(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _collections[interfaceId][instance];
}
function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance)
public
constant
returns (bool)
{
uint256 idx;
while(idx < interfaceIds.length) {
if (_collections[interfaceIds[idx]][instance]) {
return true;
}
idx += 1;
}
return false;
}
/// gets all interfaces of given instance
function getInterfacesOfInstance(address instance)
public
constant
returns (bytes4[] interfaces)
{
return _instances[instance];
}
/// sets 'instance' of singleton with interface 'interfaceId'
function setSingleton(bytes4 interfaceId, address instance)
public
only(ROLE_UNIVERSE_MANAGER)
{
setSingletonPrivate(interfaceId, instance);
}
/// convenience method for setting many singleton instances
function setManySingletons(bytes4[] interfaceIds, address[] instances)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
uint256 idx;
while(idx < interfaceIds.length) {
setSingletonPrivate(interfaceIds[idx], instances[idx]);
idx += 1;
}
}
/// set or unset 'instance' with 'interfaceId' in collection of instances
function setCollectionInterface(bytes4 interfaceId, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
setCollectionPrivate(interfaceId, instance, set);
}
/// set or unset 'instance' in many collections of instances
function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instance, set);
idx += 1;
}
}
/// set or unset array of collection
function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
require(interfaceIds.length == set_flags.length);
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]);
idx += 1;
}
}
//
// Implements IContractId
//
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0);
}
////////////////////////
// Getters
////////////////////////
function accessPolicy() public constant returns (IAccessPolicy) {
return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]);
}
function forkArbiter() public constant returns (IEthereumForkArbiter) {
return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]);
}
function neumark() public constant returns (Neumark) {
return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]);
}
function etherToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]);
}
function euroToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]);
}
function etherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ETHER_LOCK];
}
function euroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_EURO_LOCK];
}
function icbmEtherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK];
}
function icbmEuroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK];
}
function identityRegistry() public constant returns (address) {
return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]);
}
function tokenExchangeRateOracle() public constant returns (address) {
return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]);
}
function feeDisbursal() public constant returns (address) {
return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]);
}
function platformPortfolio() public constant returns (address) {
return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]);
}
function tokenExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE];
}
function gasExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE];
}
function platformTerms() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS];
}
////////////////////////
// Private methods
////////////////////////
function setSingletonPrivate(bytes4 interfaceId, address instance)
private
{
require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON");
address replacedInstance = _singletons[interfaceId];
// do nothing if not changing
if (replacedInstance != instance) {
dropInstance(replacedInstance, interfaceId);
addInstance(instance, interfaceId);
_singletons[interfaceId] = instance;
}
emit LogSetSingleton(interfaceId, instance, replacedInstance);
}
function setCollectionPrivate(bytes4 interfaceId, address instance, bool set)
private
{
// do nothing if not changing
if (_collections[interfaceId][instance] == set) {
return;
}
_collections[interfaceId][instance] = set;
if (set) {
addInstance(instance, interfaceId);
} else {
dropInstance(instance, interfaceId);
}
emit LogSetCollectionInterface(interfaceId, instance, set);
}
function addInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
// do not add null instance
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
while(idx < current.length) {
// instancy has this interface already, do nothing
if (current[idx] == interfaceId)
return;
idx += 1;
}
// new interface
current.push(interfaceId);
}
function dropInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
// do not drop null instance
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
uint256 last = current.length - 1;
while(idx <= last) {
if (current[idx] == interfaceId) {
// delete element
if (idx < last) {
// if not last element move last element to idx being deleted
current[idx] = current[last];
}
// delete last element
current.length -= 1;
return;
}
idx += 1;
}
}
} | set or unset array of collection | function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
require(interfaceIds.length == set_flags.length);
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]);
idx += 1;
}
}
| 1,801,003 |
./full_match/1/0x7FF5601B0A434b52345c57A01A28d63f3E892aC0/sources/contracts/utils/rollup/BridgeStore.sol | Sets bridge address. Emits a {SetBridge} event. slither-disable-next-line missing-zero-check | function setBridge(address newBridge) public onlyOwner {
emit SetBridge(_bridge, newBridge);
_bridge = newBridge;
}
| 16,521,940 |
./full_match/11155111/0xE46FE78DBfCa5E835667Ba9dCd3F3315E7623F8a/sources/contracts/AllowanceModule.sol | Generates the data for the transfer hash (required for signing) | function generateTransferHashData(
address safe,
address token,
address to,
uint96 amount,
address paymentToken,
uint96 payment,
uint16 nonce
) private view returns (bytes memory) {
uint256 chainId = getChainId();
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this));
bytes32 transferHash = keccak256(abi.encode(ALLOWANCE_TRANSFER_TYPEHASH, safe, token, to, amount, paymentToken, payment, nonce));
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transferHash);
}
| 3,835,132 |
pragma solidity ^0.4.23;
import "./erc721.sol";
import "./SafeMath.sol";
import "./Random.sol";
import "./Database.sol";
contract WarriorBase is ERC721
{
using SafeMath for uint256;
using SafeMath for uint64;
Random private randomContract;
Database private databaseContract;
/// @dev This emits when the token ownership changed
event Transfer(address indexed from, address indexed to, uint256 tokenId);
/// @dev This emits when user charged his warrior
event NewFund(uint _value);
/// @dev This emits when a new warrior is created(adopted) by user
event CreateWarrior(address _owner, uint newWarriorId, uint _val);
event Consequence(uint winnerId, uint loserId, address winnerAddr, address loserAddr, uint valToTransfer, uint ceToTransfer, uint winnerTitle, uint loserTitle);
event KillWarrior(uint _id, address owner, uint tokenToOwnerIndex);
event AddPrestige(uint _id, uint winningPrestige, uint title);
event SubPrestige(uint _id, uint winningPrestige);
event SetCoachCoolDownTime(uint coachId, uint attackId, uint curTime);
event SwitchRetirementStatus(uint tokenId, uint retirementStatus);
mapping (uint => address) internal tokenApprovals;
mapping (uint => address) internal tokenIndexToOwner;
mapping (address => uint) internal ownerToTokenCount;
mapping (address => uint[]) internal ownerToTokenArray;
/// the id of the given token in owner's token list.
mapping (uint => uint) internal tokenIndexToOwnerIndex;
string public constant name = "SpartaxWarrior";
string public constant symbol = "SW";
uint constant greenhandProtection = 30 minutes;
uint constant miniValue = 10 ** 16;
struct Warrior {
uint val; /// 0
uint winCount; /// 1
uint lossCount; /// 2
uint combo; /// 3
uint title; /// 4 title: default--0 primary coach--7 intermediate coach--8 advanced coach--9 master--10
uint prestige; /// 5
uint ce; /// 6 comat effectiveness
uint createTime; /// 7
uint destroyTime; /// 8
uint lastAttackCoach1; /// 9
uint lastAttackCoach2; /// 10
uint lastAttackCoach3; /// 11
uint lastAttackCoach4; /// 12
uint isRetired; /// 13
}
Warrior[] private WarriorList;
uint private ActiveWarriorListLength;
/// @dev check the given tokenId is in the tokenList and its owner is not null.
modifier tokenExist(uint256 _id) {
require(_id >= 1 && _id <= WarriorList.length);
require(tokenIndexToOwner[_id] != address(0));
_;
}
/// @dev construction method.
constructor(
address _randomContract,
address _databaseContract) public{
randomContract = Random(_randomContract);
databaseContract = Database(_databaseContract);
/// warrior list contains the 4 coaches at the very beginning
ActiveWarriorListLength = 4;
/// drop index 0
WarriorList.length += 1;
/// primary coach : value 0.01ether comat effectiveness 10 title 7
uint newWarriorId = WarriorList.length;
WarriorList.length += 1;
Warrior storage war = WarriorList[newWarriorId];
war.val = miniValue; /// 0.01 ether in Wei
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 7;
war.prestige = 0;
war.ce = 10;
_transfer(0, msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, war.val);
/// primary coach : value 0.01ether comat effectiveness 10 title 8
newWarriorId = WarriorList.length;
WarriorList.length += 1;
war = WarriorList[newWarriorId];
war.val = miniValue * 5; /// 0.05 ether in Wei
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 8;
war.prestige = 0;
war.ce = 50;
_transfer(0, msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, war.val);
/// primary coach : value 0.01ether comat effectiveness 10 title 9
newWarriorId = WarriorList.length;
WarriorList.length += 1;
war = WarriorList[newWarriorId];
war.val = miniValue * 10; /// 0.1 ether in Wei
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 9;
war.prestige = 0;
war.ce = 100;
_transfer(0, msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, war.val);
/// primary coach : value 0.01ether comat effectiveness 10 title 10
newWarriorId = WarriorList.length;
WarriorList.length += 1;
war = WarriorList[newWarriorId];
war.val = miniValue * 50; /// 0.5 ether in Wei;
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 10;
war.prestige = 0;
war.ce = 500;
_transfer(0, msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, war.val);
}
/// @dev adopt a level 1 warrior (0.01 eth)
function adoptLvOne()
external
payable
returns(uint256)
{
require(msg.sender != address(0));
require(msg.value >= 0.01 ether);
uint newWarriorId = WarriorList.length;
WarriorList.length += 1;
Warrior storage war = WarriorList[newWarriorId];
war.val = msg.value;
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 0;
war.prestige = 0;
war.ce = 10;
war.createTime = now;
war.destroyTime = 0;
war.lastAttackCoach1 = 0;
war.lastAttackCoach2 = 0;
war.lastAttackCoach3 = 0;
war.lastAttackCoach4 = 0;
_transfer(0,msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, msg.value);
ActiveWarriorListLength = ActiveWarriorListLength.add(1);
CreateWarrior(msg.sender,newWarriorId, msg.value);
return newWarriorId;
}
/// @dev adopt a level 2 warrior (0.05 eth)
function adoptLvTwo()
external
payable
returns(uint256)
{
require(msg.sender != address(0));
require(msg.value >= 0.05 ether);
uint newWarriorId = WarriorList.length;
WarriorList.length += 1;
Warrior storage war = WarriorList[newWarriorId];
war.val = msg.value;
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 0;
war.prestige = 0;
war.ce = 50;
war.createTime = now;
war.destroyTime = 0;
war.lastAttackCoach1 = 0;
war.lastAttackCoach2 = 0;
war.lastAttackCoach3 = 0;
war.lastAttackCoach4 = 0;
_transfer(0,msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, msg.value);
ActiveWarriorListLength = ActiveWarriorListLength.add(1);
CreateWarrior(msg.sender, newWarriorId, msg.value);
return newWarriorId;
}
/// @dev adopt a level 3 warrior (0.1 eth)
function adoptLvThree()
external
payable
returns(uint256)
{
require(msg.sender != address(0));
require(msg.value >= 0.1 ether);
uint newWarriorId = WarriorList.length;
WarriorList.length += 1;
Warrior storage war = WarriorList[newWarriorId];
war.val = msg.value;
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 0;
war.prestige = 0;
war.ce = 100;
war.createTime = now;
war.destroyTime = 0;
war.lastAttackCoach1 = 0;
war.lastAttackCoach2 = 0;
war.lastAttackCoach3 = 0;
war.lastAttackCoach4 = 0;
_transfer(0,msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, msg.value);
ActiveWarriorListLength = ActiveWarriorListLength.add(1);
CreateWarrior(msg.sender, newWarriorId, msg.value);
return newWarriorId;
}
/// @dev adopt a level 4 warrior (0.5 eth)
function adoptLvFour()
external
payable
returns(uint256)
{
require(msg.sender != address(0));
require(msg.value >= 0.5 ether);
uint newWarriorId = WarriorList.length;
WarriorList.length += 1;
Warrior storage war = WarriorList[newWarriorId];
war.val = msg.value;
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 0;
war.prestige = 0;
war.ce = 500;
war.createTime = now;
war.destroyTime = 0;
war.lastAttackCoach1 = 0;
war.lastAttackCoach2 = 0;
war.lastAttackCoach3 = 0;
war.lastAttackCoach4 = 0;
_transfer(0,msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, msg.value);
ActiveWarriorListLength = ActiveWarriorListLength.add(1);
CreateWarrior(msg.sender, newWarriorId, msg.value);
return newWarriorId;
}
function setRandomAddr(address _randomContract) external {
randomContract = Random(_randomContract);
}
/// @dev return the total number of tokens in the game
function getTokenNum() external view returns(uint) {
return WarriorList.length - 1;
}
/// @dev return the owner address of the token(warrior)
function getTokenOwner(uint _id) external view tokenExist(_id) returns(address) {
require(tokenIndexToOwner[_id] != address(0));
return tokenIndexToOwner[_id];
}
/// @dev Ruturn token details by tokenId
function getToken(uint256 _id) external view tokenExist(_id) returns (uint[14] datas) {
Warrior storage warrior = WarriorList[_id];
datas[0] = warrior.val;
datas[1] = warrior.winCount;
datas[2] = warrior.lossCount;
datas[3] = warrior.combo;
datas[4] = warrior.title;
datas[5] = warrior.prestige;
datas[6] = warrior.ce;
datas[7] = warrior.createTime;
datas[8] = warrior.destroyTime;
datas[9] = warrior.lastAttackCoach1;
datas[10] = warrior.lastAttackCoach2;
datas[11] = warrior.lastAttackCoach3;
datas[12] = warrior.lastAttackCoach4;
datas[13] = warrior.isRetired;
}
/// @dev return all tokens owned by owner
function getOwnTokens(address _owner) external view returns(uint256[] tokens){
require(_owner != address(0));
uint256[] memory tokenArray = ownerToTokenArray[_owner];
uint256 length = (uint256)(tokenArray.length);
tokens = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
tokens[i] = tokenArray[i];
}
}
/// @dev return all tokens not belong to owner
function getEnemyTokens(address _owner) external view returns(uint[] tokens) {
require(_owner != address(0));
uint length = WarriorList.length - 1 - ownerToTokenArray[_owner].length;
tokens = new uint256[](length);
uint index = 0;
for (uint256 i = 1; i < WarriorList.length; ++i) {
if (tokenIndexToOwner[i] != _owner && tokenIndexToOwner[i] != address(0)) {
tokens[index] = i;
index += 1;
}
}
}
/// @dev return active warrior numbers for now
function getActiveWarriorListLength() external view returns(uint) {
return ActiveWarriorListLength;
}
/// @dev set the timestamp of attacking each coach, you cannot attack them twice within an hour
function setCoachCoolDownTime(uint coachId, uint attackId) external tokenExist(attackId){
Warrior storage attacker = WarriorList[attackId];
if (coachId == 1)
attacker.lastAttackCoach1 = uint(now);
else if (coachId == 2)
attacker.lastAttackCoach2 = uint(now);
else if (coachId == 3)
attacker.lastAttackCoach3 = uint(now);
else if (coachId == 4)
attacker.lastAttackCoach4 = uint(now);
emit SetCoachCoolDownTime(coachId, attackId, now);
}
/// @dev calculate the consequece of a finished battle
function consequence(
uint winnerId,
uint loserId,
address winnerAddr,
address loserAddr) external tokenExist(winnerId) tokenExist(loserId) returns(uint){
require(tokenIndexToOwner[winnerId] == winnerAddr);
require(tokenIndexToOwner[loserId] == loserAddr);
uint valToTransfer;
uint ceToTransfer;
if (WarriorList[loserId].ce <= 2) {
valToTransfer = WarriorList[loserId].val;
ceToTransfer = WarriorList[loserId].ce;
} else {
valToTransfer = WarriorList[loserId].val.div(2);
ceToTransfer = WarriorList[loserId].ce.div(2);
}
Warrior storage winner = WarriorList[winnerId];
winner.winCount = winner.winCount.add(1);
winner.combo = winner.combo.add(1);
Warrior storage loser = WarriorList[loserId];
loser.lossCount = loser.lossCount.add(1);
loser.combo = 0;
if (loser.title < 7 || loser.title > 10) /// if the loser is a coach, his value shall not be reduced.
{
loser.val = loser.val.sub(valToTransfer);
loser.title = 0;
loser.ce = loser.ce.sub(ceToTransfer);
}
if (winner.title < 7 || winner.title > 10) {
winner.val = winner.val.add(valToTransfer);
winner.ce = winner.ce.add(ceToTransfer);
if (winner.title < 7)
{
if (winner.combo < 1)
winner.title = 0;
else if (winner.combo < 2)
winner.title = 1;
else if (winner.combo < 4)
winner.title = 2;
else if (winner.combo < 8)
winner.title = 3;
else if (winner.combo < 12)
winner.title = 4;
else if (winner.combo < 20)
winner.title = 5;
else
winner.title = 6;
}
}
emit Consequence(winnerId,loserId, winnerAddr, loserAddr, valToTransfer, ceToTransfer, winner.title, loser.title);
return valToTransfer;
}
function addPrestige(uint tokenId, uint prestigeAmt) tokenExist(tokenId) external {
WarriorList[tokenId].prestige = WarriorList[tokenId].prestige.add(prestigeAmt);
if ( WarriorList[tokenId].prestige >= 30 )
WarriorList[tokenId].title = 11;
if ( WarriorList[tokenId].prestige >= 40 )
WarriorList[tokenId].title = 12;
emit AddPrestige(tokenId, prestigeAmt, WarriorList[tokenId].title);
}
function subPrestige(uint tokenId, uint prestigeAmt) tokenExist(tokenId) external {
WarriorList[tokenId].prestige = WarriorList[tokenId].prestige.sub(prestigeAmt);
WarriorList[tokenId].title = 0;
if ( WarriorList[tokenId].prestige >= 30 )
WarriorList[tokenId].title = 11;
if ( WarriorList[tokenId].prestige >= 40 )
WarriorList[tokenId].title = 12;
emit SubPrestige(tokenId, prestigeAmt);
}
function switchRetirementStatus(uint tokenId) tokenExist(tokenId) external {
require(WarriorList[tokenId].title == 12);
WarriorList[tokenId].isRetired = 1 - WarriorList[tokenId].isRetired;
emit SwitchRetirementStatus(tokenId, WarriorList[tokenId].isRetired);
}
/// @dev "feed" the token with msg.value
function feedWarrior(uint _id) public tokenExist(_id) payable returns(uint) {
require(tokenIndexToOwner[_id] == msg.sender);
WarriorList[_id].val = WarriorList[_id].val.add(msg.value);
databaseContract.addAccountEth(msg.sender, msg.value);
NewFund(this.balance);
return this.balance;
}
function _removeFromList(uint _id, address _owner) private {
for (uint i = 0; i < ownerToTokenArray[_owner].length; i++) {
if (ownerToTokenArray[_owner][i] == _id) {
for (uint j = i; j < ownerToTokenArray[_owner].length - 1; j++)
ownerToTokenArray[_owner][j] = ownerToTokenArray[_owner][j + 1];
ownerToTokenArray[_owner].length -= 1;
return;
}
}
}
/// @dev "kill" the token and sent its ether value back to owner's wallet
function killWarrior(uint _id) external tokenExist(_id) returns(uint) {
require(tokenIndexToOwner[_id] == msg.sender);
uint valToTransfer = WarriorList[_id].val;
uint tokenToOwnerIndex = tokenIndexToOwnerIndex[_id];
_removeFromList(_id, msg.sender);
tokenIndexToOwner[_id] = address(0);
ownerToTokenCount[msg.sender] = ownerToTokenCount[msg.sender].sub(1);
tokenIndexToOwnerIndex[_id] = 0;
databaseContract.reduceAccountEth(msg.sender,valToTransfer);
ActiveWarriorListLength = ActiveWarriorListLength.sub(1);
msg.sender.transfer(valToTransfer);
emit KillWarrior(_id, msg.sender, tokenToOwnerIndex);
return tokenToOwnerIndex;
}
function addFund() public payable returns(uint) {
require(msg.value > 0);
emit NewFund(this.balance);
return this.balance;
}
function getBalance() external returns(uint){
return this.balance;
}
function _transfer(address _from, address _to, uint256 _tokenId) internal {
if (_from != address(0)){
uint256 indexFrom = tokenIndexToOwnerIndex[_tokenId];
uint256[] storage tokenArray = ownerToTokenArray[_from];
require(tokenArray[indexFrom] == _tokenId);
if (indexFrom != tokenArray.length - 1){
uint256 lastTokenId = tokenArray[tokenArray.length - 1];
tokenArray[indexFrom] = lastTokenId;
tokenIndexToOwnerIndex[lastTokenId] = indexFrom;
}
tokenArray.length.sub(1);
}
/// Transfer the token to address '_to'
tokenIndexToOwner[_tokenId] = _to;
if (ownerToTokenArray[_to].length == 0){
ownerToTokenCount[_to] = 0;
}
ownerToTokenArray[_to].push(_tokenId);
ownerToTokenCount[_to] = ownerToTokenCount[_to].add(1);
tokenIndexToOwnerIndex[_tokenId] = (uint256)(ownerToTokenArray[_to].length.sub(1));
emit Transfer(_from, _to, _tokenId);
}
///@dev The function is to be called by former owner to tranfer the token to the new owner himself.
function transfer(address _to, uint256 _tokenId) external{
require(msg.sender == tokenIndexToOwner[_tokenId]);
require(_to != 0x0);
_transfer(msg.sender, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) external{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
require(_to != address(this));
// Check for approval and valid ownership
//require(_approvedFor(msg.sender, _tokenId));
require(ownerOf(_tokenId) == _from);
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return WarriorList.length - 1;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownerToTokenCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
_owner = tokenIndexToOwner[_tokenId];
require(_owner != address(0));
}
///@dev The function is to be called by new owner to get the token from the former owner himself.
function takeOwnership(uint256 _tokenId) public {
require(tokenApprovals[_tokenId] == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
///@dev The function is to be called by former owner to assign the token ownership to the new owner.
function approve(address _to, uint256 _tokenId) external{
require(msg.sender == tokenIndexToOwner[_tokenId]);
tokenApprovals[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function destroyWeaponById(uint256 _tokenId) public {
require(msg.sender == tokenIndexToOwner[_tokenId]);
}
// ERC721
function supportsInterface(bytes4 _interfaceId) external view returns(bool) {
// ERC165 || ERC721 || ERC165^ERC721
return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff);
}
}
| adopt a level 2 warrior (0.05 eth) | function adoptLvTwo()
external
payable
returns(uint256)
{
require(msg.sender != address(0));
require(msg.value >= 0.05 ether);
uint newWarriorId = WarriorList.length;
WarriorList.length += 1;
Warrior storage war = WarriorList[newWarriorId];
war.val = msg.value;
war.winCount = 0;
war.lossCount = 0;
war.combo = 0;
war.title = 0;
war.prestige = 0;
war.ce = 50;
war.createTime = now;
war.destroyTime = 0;
war.lastAttackCoach1 = 0;
war.lastAttackCoach2 = 0;
war.lastAttackCoach3 = 0;
war.lastAttackCoach4 = 0;
_transfer(0,msg.sender, newWarriorId);
databaseContract.addAccountEth(msg.sender, msg.value);
ActiveWarriorListLength = ActiveWarriorListLength.add(1);
CreateWarrior(msg.sender, newWarriorId, msg.value);
return newWarriorId;
}
| 1,821,250 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Transaction tracker
* @notice An ownable to track transactions of generic types
*/
contract TransactionTracker is Ownable, Servable {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct TransactionRecord {
int256 value;
uint256 blockNumber;
address currencyCt;
uint256 currencyId;
}
struct TransactionLog {
TransactionRecord[] records;
mapping(address => mapping(uint256 => uint256[])) recordIndicesByCurrency;
}
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSIT_TRANSACTION_TYPE = "deposit";
string constant public WITHDRAWAL_TRANSACTION_TYPE = "withdrawal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositTransactionType;
bytes32 public withdrawalTransactionType;
mapping(address => mapping(bytes32 => TransactionLog)) private transactionLogByWalletType;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositTransactionType = keccak256(abi.encodePacked(DEPOSIT_TRANSACTION_TYPE));
withdrawalTransactionType = keccak256(abi.encodePacked(WITHDRAWAL_TRANSACTION_TYPE));
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add a transaction record of the given wallet, type, value and currency
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param value The concerned value (amount of fungible, id of non-fungible)
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function add(address wallet, bytes32 _type, int256 value, address currencyCt,
uint256 currencyId)
public
onlyActiveService
{
transactionLogByWalletType[wallet][_type].records.length++;
uint256 index = transactionLogByWalletType[wallet][_type].records.length - 1;
transactionLogByWalletType[wallet][_type].records[index].value = value;
transactionLogByWalletType[wallet][_type].records[index].blockNumber = block.number;
transactionLogByWalletType[wallet][_type].records[index].currencyCt = currencyCt;
transactionLogByWalletType[wallet][_type].records[index].currencyId = currencyId;
transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].push(index);
}
/// @notice Get the number of transaction records for the given wallet and type
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @return The count of transaction records
function count(address wallet, bytes32 _type)
public
view
returns (uint256)
{
return transactionLogByWalletType[wallet][_type].records.length;
}
/// @notice Get the transaction record for the given wallet and type by the given index
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param index The concerned log index
/// @return The transaction record
function getByIndex(address wallet, bytes32 _type, uint256 index)
public
view
returns (int256 value, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
TransactionRecord storage entry = transactionLogByWalletType[wallet][_type].records[index];
value = entry.value;
blockNumber = entry.blockNumber;
currencyCt = entry.currencyCt;
currencyId = entry.currencyId;
}
/// @notice Get the transaction record for the given wallet and type by the given block number
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param _blockNumber The concerned block number
/// @return The transaction record
function getByBlockNumber(address wallet, bytes32 _type, uint256 _blockNumber)
public
view
returns (int256 value, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return getByIndex(wallet, _type, _indexByBlockNumber(wallet, _type, _blockNumber));
}
/// @notice Get the number of transaction records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of transaction records
function countByCurrency(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId)
public
view
returns (uint256)
{
return transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].length;
}
/// @notice Get the transaction record for the given wallet, type and currency by the given index
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param index The concerned log index
/// @return The transaction record
function getByCurrencyIndex(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId, uint256 index)
public
view
returns (int256 value, uint256 blockNumber)
{
uint256 entryIndex = transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId][index];
TransactionRecord storage entry = transactionLogByWalletType[wallet][_type].records[entryIndex];
value = entry.value;
blockNumber = entry.blockNumber;
}
/// @notice Get the transaction record for the given wallet, type and currency by the given block number
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param _blockNumber The concerned block number
/// @return The transaction record
function getByCurrencyBlockNumber(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId, uint256 _blockNumber)
public
view
returns (int256 value, uint256 blockNumber)
{
return getByCurrencyIndex(
wallet, _type, currencyCt, currencyId,
_indexByCurrencyBlockNumber(
wallet, _type, currencyCt, currencyId, _blockNumber
)
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _indexByBlockNumber(address wallet, bytes32 _type, uint256 blockNumber)
private
view
returns (uint256)
{
require(
0 < transactionLogByWalletType[wallet][_type].records.length,
"No transactions found for wallet and type [TransactionTracker.sol:187]"
);
for (uint256 i = transactionLogByWalletType[wallet][_type].records.length - 1; i >= 0; i--)
if (blockNumber >= transactionLogByWalletType[wallet][_type].records[i].blockNumber)
return i;
revert();
}
function _indexByCurrencyBlockNumber(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId, uint256 blockNumber)
private
view
returns (uint256)
{
require(
0 < transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].length,
"No transactions found for wallet, type and currency [TransactionTracker.sol:203]"
);
for (uint256 i = transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].length - 1; i >= 0; i--) {
uint256 j = transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId][i];
if (blockNumber >= transactionLogByWalletType[wallet][_type].records[j].blockNumber)
return j;
}
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransactionTrackable
* @notice An ownable that has a transaction tracker property
*/
contract TransactionTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransactionTracker public transactionTracker;
bool public transactionTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransactionTrackerEvent(TransactionTracker oldTransactionTracker, TransactionTracker newTransactionTracker);
event FreezeTransactionTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the transaction tracker contract
/// @param newTransactionTracker The (address of) TransactionTracker contract instance
function setTransactionTracker(TransactionTracker newTransactionTracker)
public
onlyDeployer
notNullAddress(address(newTransactionTracker))
notSameAddresses(address(newTransactionTracker), address(transactionTracker))
{
// Require that this contract has not been frozen
require(!transactionTrackerFrozen, "Transaction tracker frozen [TransactionTrackable.sol:43]");
// Update fields
TransactionTracker oldTransactionTracker = transactionTracker;
transactionTracker = newTransactionTracker;
// Emit event
emit SetTransactionTrackerEvent(oldTransactionTracker, newTransactionTracker);
}
/// @notice Freeze the transaction tracker from further updates
/// @dev This operation can not be undone
function freezeTransactionTracker()
public
onlyDeployer
{
transactionTrackerFrozen = true;
// Emit event
emit FreezeTransactionTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transactionTrackerInitialized() {
require(address(transactionTracker) != address(0), "Transaction track not initialized [TransactionTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueToken
* @dev Implementation of the EIP20 standard token (also known as ERC20 token) with added
* calculation of balance blocks at every transfer.
*/
contract RevenueToken is ERC20Mintable {
using SafeMath for uint256;
bool public mintingDisabled;
address[] public holders;
mapping(address => bool) public holdersMap;
mapping(address => uint256[]) public balances;
mapping(address => uint256[]) public balanceBlocks;
mapping(address => uint256[]) public balanceBlockNumbers;
event DisableMinting();
/**
* @notice Disable further minting
* @dev This operation can not be undone
*/
function disableMinting()
public
onlyMinter
{
mintingDisabled = true;
emit DisableMinting();
}
/**
* @notice Mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value)
public
onlyMinter
returns (bool)
{
require(!mintingDisabled, "Minting disabled [RevenueToken.sol:60]");
// Call super's mint, including event emission
bool minted = super.mint(to, value);
if (minted) {
// Adjust balance blocks
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return minted;
}
/**
* @notice Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value)
public
returns (bool)
{
// Call super's transfer, including event emission
bool transferred = super.transfer(to, value);
if (transferred) {
// Adjust balance blocks
addBalanceBlocks(msg.sender);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @dev Beware that 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
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
returns (bool)
{
// Prevent the update of non-zero allowance
require(
0 == value || 0 == allowance(msg.sender, spender),
"Value or allowance non-zero [RevenueToken.sol:121]"
);
// Call super's approve, including event emission
return super.approve(spender, value);
}
/**
* @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
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint256 value)
public
returns (bool)
{
// Call super's transferFrom, including event emission
bool transferred = super.transferFrom(from, to, value);
if (transferred) {
// Adjust balance blocks
addBalanceBlocks(from);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
/**
* @notice Calculate the amount of balance blocks, i.e. the area under the curve (AUC) of
* balance as function of block number
* @dev The AUC is used as weight for the share of revenue that a token holder may claim
* @param account The account address for which calculation is done
* @param startBlock The start block number considered
* @param endBlock The end block number considered
* @return The calculated AUC
*/
function balanceBlocksIn(address account, uint256 startBlock, uint256 endBlock)
public
view
returns (uint256)
{
require(startBlock < endBlock, "Bounds parameters mismatch [RevenueToken.sol:173]");
require(account != address(0), "Account is null address [RevenueToken.sol:174]");
if (balanceBlockNumbers[account].length == 0 || endBlock < balanceBlockNumbers[account][0])
return 0;
uint256 i = 0;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < startBlock)
i++;
uint256 r;
if (i >= balanceBlockNumbers[account].length)
r = balances[account][balanceBlockNumbers[account].length - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : balanceBlockNumbers[account][i - 1];
uint256 h = balanceBlockNumbers[account][i];
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : balanceBlocks[account][i].mul(h).div(balanceBlockNumbers[account][i].sub(l));
i++;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < endBlock) {
r = r.add(balanceBlocks[account][i]);
i++;
}
if (i >= balanceBlockNumbers[account].length)
r = r.add(
balances[account][balanceBlockNumbers[account].length - 1].mul(
endBlock.sub(balanceBlockNumbers[account][balanceBlockNumbers[account].length - 1])
)
);
else if (balanceBlockNumbers[account][i - 1] < endBlock)
r = r.add(
balanceBlocks[account][i].mul(
endBlock.sub(balanceBlockNumbers[account][i - 1])
).div(
balanceBlockNumbers[account][i].sub(balanceBlockNumbers[account][i - 1])
)
);
}
return r;
}
/**
* @notice Get the count of balance updates for the given account
* @return The count of balance updates
*/
function balanceUpdatesCount(address account)
public
view
returns (uint256)
{
return balanceBlocks[account].length;
}
/**
* @notice Get the count of holders
* @return The count of holders
*/
function holdersCount()
public
view
returns (uint256)
{
return holders.length;
}
/**
* @notice Get the subset of holders (optionally with positive balance only) in the given 0 based index range
* @param low The lower inclusive index
* @param up The upper inclusive index
* @param posOnly List only positive balance holders
* @return The subset of positive balance registered holders in the given range
*/
function holdersByIndices(uint256 low, uint256 up, bool posOnly)
public
view
returns (address[] memory)
{
require(low <= up, "Bounds parameters mismatch [RevenueToken.sol:259]");
up = up > holders.length - 1 ? holders.length - 1 : up;
uint256 length = 0;
if (posOnly) {
for (uint256 i = low; i <= up; i++)
if (0 < balanceOf(holders[i]))
length++;
} else
length = up - low + 1;
address[] memory _holders = new address[](length);
uint256 j = 0;
for (uint256 i = low; i <= up; i++)
if (!posOnly || 0 < balanceOf(holders[i]))
_holders[j++] = holders[i];
return _holders;
}
function addBalanceBlocks(address account)
private
{
uint256 length = balanceBlockNumbers[account].length;
balances[account].push(balanceOf(account));
if (0 < length)
balanceBlocks[account].push(
balances[account][length - 1].mul(
block.number.sub(balanceBlockNumbers[account][length - 1])
)
);
else
balanceBlocks[account].push(0);
balanceBlockNumbers[account].push(block.number);
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(address(this), spender) == 0));
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);
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 equal true).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable that allows a beneficiary to extract tokens in
* a number of batches each a given release time
*/
contract TokenMultiTimelock is Ownable {
using SafeERC20 for IERC20;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Release {
uint256 earliestReleaseTime;
uint256 amount;
uint256 blockNumber;
bool done;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
IERC20 public token;
address public beneficiary;
Release[] public releases;
uint256 public totalLockedAmount;
uint256 public executedReleasesCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTokenEvent(IERC20 token);
event SetBeneficiaryEvent(address beneficiary);
event DefineReleaseEvent(uint256 earliestReleaseTime, uint256 amount, uint256 blockNumber);
event SetReleaseBlockNumberEvent(uint256 index, uint256 blockNumber);
event ReleaseEvent(uint256 index, uint256 blockNumber, uint256 earliestReleaseTime,
uint256 actualReleaseTime, uint256 amount);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer)
Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the address of token
/// @param _token The address of token
function setToken(IERC20 _token)
public
onlyOperator
notNullOrThisAddress(address(_token))
{
// Require that the token has not previously been set
require(address(token) == address(0), "Token previously set [TokenMultiTimelock.sol:73]");
// Update beneficiary
token = _token;
// Emit event
emit SetTokenEvent(token);
}
/// @notice Set the address of beneficiary
/// @param _beneficiary The new address of beneficiary
function setBeneficiary(address _beneficiary)
public
onlyOperator
notNullAddress(_beneficiary)
{
// Update beneficiary
beneficiary = _beneficiary;
// Emit event
emit SetBeneficiaryEvent(beneficiary);
}
/// @notice Define a set of new releases
/// @param earliestReleaseTimes The timestamp after which the corresponding amount may be released
/// @param amounts The amounts to be released
/// @param releaseBlockNumbers The set release block numbers for releases whose earliest release time
/// is in the past
function defineReleases(uint256[] memory earliestReleaseTimes, uint256[] memory amounts, uint256[] memory releaseBlockNumbers)
onlyOperator
public
{
require(
earliestReleaseTimes.length == amounts.length,
"Earliest release times and amounts lengths mismatch [TokenMultiTimelock.sol:105]"
);
require(
earliestReleaseTimes.length >= releaseBlockNumbers.length,
"Earliest release times and release block numbers lengths mismatch [TokenMultiTimelock.sol:109]"
);
// Require that token address has been set
require(address(token) != address(0), "Token not initialized [TokenMultiTimelock.sol:115]");
for (uint256 i = 0; i < earliestReleaseTimes.length; i++) {
// Update the total amount locked by this contract
totalLockedAmount += amounts[i];
// Require that total amount locked is less than or equal to the token balance of
// this contract
require(token.balanceOf(address(this)) >= totalLockedAmount, "Total locked amount overrun [TokenMultiTimelock.sol:123]");
// Retrieve early block number where available
uint256 blockNumber = i < releaseBlockNumbers.length ? releaseBlockNumbers[i] : 0;
// Add release
releases.push(Release(earliestReleaseTimes[i], amounts[i], blockNumber, false));
// Emit event
emit DefineReleaseEvent(earliestReleaseTimes[i], amounts[i], blockNumber);
}
}
/// @notice Get the count of releases
/// @return The number of defined releases
function releasesCount()
public
view
returns (uint256)
{
return releases.length;
}
/// @notice Set the block number of a release that is not done
/// @param index The index of the release
/// @param blockNumber The updated block number
function setReleaseBlockNumber(uint256 index, uint256 blockNumber)
public
onlyBeneficiary
{
// Require that the release is not done
require(!releases[index].done, "Release previously done [TokenMultiTimelock.sol:154]");
// Update the release block number
releases[index].blockNumber = blockNumber;
// Emit event
emit SetReleaseBlockNumberEvent(index, blockNumber);
}
/// @notice Transfers tokens held in the indicated release to beneficiary.
/// @param index The index of the release
function release(uint256 index)
public
onlyBeneficiary
{
// Get the release object
Release storage _release = releases[index];
// Require that this release has been properly defined by having non-zero amount
require(0 < _release.amount, "Release amount not strictly positive [TokenMultiTimelock.sol:173]");
// Require that this release has not already been executed
require(!_release.done, "Release previously done [TokenMultiTimelock.sol:176]");
// Require that the current timestamp is beyond the nominal release time
require(block.timestamp >= _release.earliestReleaseTime, "Block time stamp less than earliest release time [TokenMultiTimelock.sol:179]");
// Set release done
_release.done = true;
// Set release block number if not previously set
if (0 == _release.blockNumber)
_release.blockNumber = block.number;
// Bump number of executed releases
executedReleasesCount++;
// Decrement the total locked amount
totalLockedAmount -= _release.amount;
// Execute transfer
token.safeTransfer(beneficiary, _release.amount);
// Emit event
emit ReleaseEvent(index, _release.blockNumber, _release.earliestReleaseTime, block.timestamp, _release.amount);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyBeneficiary() {
require(msg.sender == beneficiary, "Message sender not beneficiary [TokenMultiTimelock.sol:204]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
contract RevenueTokenManager is TokenMultiTimelock {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256[] public totalReleasedAmounts;
uint256[] public totalReleasedAmountBlocks;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer)
public
TokenMultiTimelock(deployer)
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Transfers tokens held in the indicated release to beneficiary
/// and update amount blocks
/// @param index The index of the release
function release(uint256 index)
public
onlyBeneficiary
{
// Call release of multi timelock
super.release(index);
// Add amount blocks
_addAmountBlocks(index);
}
/// @notice Calculate the released amount blocks, i.e. the area under the curve (AUC) of
/// release amount as function of block number
/// @param startBlock The start block number considered
/// @param endBlock The end block number considered
/// @return The calculated AUC
function releasedAmountBlocksIn(uint256 startBlock, uint256 endBlock)
public
view
returns (uint256)
{
require(startBlock < endBlock, "Bounds parameters mismatch [RevenueTokenManager.sol:60]");
if (executedReleasesCount == 0 || endBlock < releases[0].blockNumber)
return 0;
uint256 i = 0;
while (i < executedReleasesCount && releases[i].blockNumber < startBlock)
i++;
uint256 r;
if (i >= executedReleasesCount)
r = totalReleasedAmounts[executedReleasesCount - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : releases[i - 1].blockNumber;
uint256 h = releases[i].blockNumber;
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : totalReleasedAmountBlocks[i].mul(h).div(releases[i].blockNumber.sub(l));
i++;
while (i < executedReleasesCount && releases[i].blockNumber < endBlock) {
r = r.add(totalReleasedAmountBlocks[i]);
i++;
}
if (i >= executedReleasesCount)
r = r.add(
totalReleasedAmounts[executedReleasesCount - 1].mul(
endBlock.sub(releases[executedReleasesCount - 1].blockNumber)
)
);
else if (releases[i - 1].blockNumber < endBlock)
r = r.add(
totalReleasedAmountBlocks[i].mul(
endBlock.sub(releases[i - 1].blockNumber)
).div(
releases[i].blockNumber.sub(releases[i - 1].blockNumber)
)
);
}
return r;
}
/// @notice Get the block number of the release
/// @param index The index of the release
/// @return The block number of the release;
function releaseBlockNumbers(uint256 index)
public
view
returns (uint256)
{
return releases[index].blockNumber;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _addAmountBlocks(uint256 index)
private
{
// Push total amount released and total released amount blocks
if (0 < index) {
totalReleasedAmounts.push(
totalReleasedAmounts[index - 1] + releases[index].amount
);
totalReleasedAmountBlocks.push(
totalReleasedAmounts[index - 1].mul(
releases[index].blockNumber.sub(releases[index - 1].blockNumber)
)
);
} else {
totalReleasedAmounts.push(releases[index].amount);
totalReleasedAmountBlocks.push(0);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TokenHolderRevenueFund
* @notice Fund that manages the revenue earned by revenue token holders.
*/
contract TokenHolderRevenueFund is Ownable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CLOSE_ACCRUAL_PERIOD_ACTION = "close_accrual_period";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
RevenueTokenManager public revenueTokenManager;
FungibleBalanceLib.Balance private periodAccrual;
CurrenciesLib.Currencies private periodCurrencies;
FungibleBalanceLib.Balance private aggregateAccrual;
CurrenciesLib.Currencies private aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
mapping(address => mapping(address => mapping(uint256 => uint256[]))) public claimedAccrualBlockNumbersByWalletCurrency;
mapping(address => mapping(uint256 => uint256[])) public accrualBlockNumbersByCurrency;
mapping(address => mapping(uint256 => mapping(uint256 => int256))) public aggregateAccrualAmountByCurrencyBlockNumber;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetRevenueTokenManagerEvent(RevenueTokenManager oldRevenueTokenManager,
RevenueTokenManager newRevenueTokenManager);
event ReceiveEvent(address wallet, int256 amount, address currencyCt,
uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent(int256 periodAmount, int256 aggregateAmount, address currencyCt,
uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address wallet, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndTransferToBeneficiaryByProxyEvent(address wallet, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId,
string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the revenue token manager contract
/// @param newRevenueTokenManager The (address of) RevenueTokenManager contract instance
function setRevenueTokenManager(RevenueTokenManager newRevenueTokenManager)
public
onlyDeployer
notNullAddress(address(newRevenueTokenManager))
{
if (newRevenueTokenManager != revenueTokenManager) {
// Set new revenue token
RevenueTokenManager oldRevenueTokenManager = revenueTokenManager;
revenueTokenManager = newRevenueTokenManager;
// Emit event
emit SetRevenueTokenManagerEvent(oldRevenueTokenManager, newRevenueTokenManager);
}
}
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to in-use lists
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId,
string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [TokenHolderRevenueFund.sol:157]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [TokenHolderRevenueFund.sol:166]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to in-use lists
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the staged balance of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The staged balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyEnabledServiceAction(CLOSE_ACCRUAL_PERIOD_ACTION)
{
// Clear period accrual stats
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
// Get the amount of the accrual period
int256 periodAmount = periodAccrual.get(currency.ct, currency.id);
// Register this block number as accrual block number of currency
accrualBlockNumbersByCurrency[currency.ct][currency.id].push(block.number);
// Store the aggregate accrual balance of currency at this block number
aggregateAccrualAmountByCurrencyBlockNumber[currency.ct][currency.id][block.number] = aggregateAccrualBalance(
currency.ct, currency.id
);
if (periodAmount > 0) {
// Reset period accrual of currency
periodAccrual.set(0, currency.ct, currency.id);
// Remove currency from period in-use list
periodCurrencies.removeByCurrency(currency.ct, currency.id);
}
// Emit event
emit CloseAccrualPeriodEvent(
periodAmount,
aggregateAccrualAmountByCurrencyBlockNumber[currency.ct][currency.id][block.number],
currency.ct, currency.id
);
}
}
/// @notice Claim accrual and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param destWallet The concerned destination wallet of the transfer
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, address destWallet, string memory balanceType,
address currencyCt, uint256 currencyId, string memory standard)
public
{
// Claim accrual and obtain the claimed amount
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Transfer ETH to the beneficiary
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(destWallet, balanceType);
else {
// Approve of beneficiary
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [TokenHolderRevenueFund.sol:349]");
// Transfer tokens to the beneficiary
beneficiary.receiveTokensTo(destWallet, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim accrual and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim accrual and obtain the claimed amount
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Update staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [TokenHolderRevenueFund.sol:384]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [TokenHolderRevenueFund.sol:403]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Require that at least one accrual period has terminated
require(0 < accrualBlockNumbersByCurrency[currencyCt][currencyId].length, "No terminated accrual period found [TokenHolderRevenueFund.sol:418]");
// Calculate lower block number as last accrual block number claimed for currency c by wallet OR 0
uint256[] storage claimedAccrualBlockNumbers = claimedAccrualBlockNumbersByWalletCurrency[wallet][currencyCt][currencyId];
uint256 bnLow = (0 == claimedAccrualBlockNumbers.length ? 0 : claimedAccrualBlockNumbers[claimedAccrualBlockNumbers.length - 1]);
// Set upper block number as last accrual block number
uint256 bnUp = accrualBlockNumbersByCurrency[currencyCt][currencyId][accrualBlockNumbersByCurrency[currencyCt][currencyId].length - 1];
// Require that lower block number is below upper block number
require(bnLow < bnUp, "Bounds parameters mismatch [TokenHolderRevenueFund.sol:428]");
// Calculate the amount that is claimable in the span between lower and upper block numbers
int256 claimableAmount = aggregateAccrualAmountByCurrencyBlockNumber[currencyCt][currencyId][bnUp]
- (0 == bnLow ? 0 : aggregateAccrualAmountByCurrencyBlockNumber[currencyCt][currencyId][bnLow]);
// Require that claimable amount is strictly positive
require(claimableAmount.isNonZeroPositiveInt256(), "Claimable amount not strictly positive [TokenHolderRevenueFund.sol:435]");
// Retrieve the balance blocks of wallet
int256 walletBalanceBlocks = int256(
RevenueToken(address(revenueTokenManager.token())).balanceBlocksIn(wallet, bnLow, bnUp)
);
// Retrieve the released amount blocks
int256 releasedAmountBlocks = int256(
revenueTokenManager.releasedAmountBlocksIn(bnLow, bnUp)
);
// Calculate the claimed amount
int256 claimedAmount = walletBalanceBlocks.mul_nn(claimableAmount).mul_nn(1e18).div_nn(releasedAmountBlocks.mul_nn(1e18));
// Store upper bound as the last claimed accrual block number for currency
claimedAccrualBlockNumbers.push(bnUp);
// Return the claimed amount
return claimedAmount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Client fund
* @notice Where clients’ crypto is deposited into, staged and withdrawn from.
*/
contract ClientFund is Ownable, Beneficiary, Benefactor, AuthorizableServable, TransferControllerManageable,
BalanceTrackable, TransactionTrackable, WalletLockable {
using SafeMathIntLib for int256;
address[] public seizedWallets;
mapping(address => bool) public seizedByWallet;
TokenHolderRevenueFund public tokenHolderRevenueFund;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTokenHolderRevenueFundEvent(TokenHolderRevenueFund oldTokenHolderRevenueFund,
TokenHolderRevenueFund newTokenHolderRevenueFund);
event ReceiveEvent(address wallet, string balanceType, int256 value, address currencyCt,
uint256 currencyId, string standard);
event WithdrawEvent(address wallet, int256 value, address currencyCt, uint256 currencyId,
string standard);
event StageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId,
string standard);
event UnstageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId,
string standard);
event UpdateSettledBalanceEvent(address wallet, int256 value, address currencyCt,
uint256 currencyId);
event StageToBeneficiaryEvent(address sourceWallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string standard);
event TransferToBeneficiaryEvent(address wallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string standard);
event SeizeBalancesEvent(address seizedWallet, address seizerWallet, int256 value,
address currencyCt, uint256 currencyId);
event ClaimRevenueEvent(address claimer, string balanceType, address currencyCt,
uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Beneficiary() Benefactor()
public
{
serviceActivationTimeout = 1 weeks;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the token holder revenue fund contract
/// @param newTokenHolderRevenueFund The (address of) TokenHolderRevenueFund contract instance
function setTokenHolderRevenueFund(TokenHolderRevenueFund newTokenHolderRevenueFund)
public
onlyDeployer
notNullAddress(address(newTokenHolderRevenueFund))
notSameAddresses(address(newTokenHolderRevenueFund), address(tokenHolderRevenueFund))
{
// Set new token holder revenue fund
TokenHolderRevenueFund oldTokenHolderRevenueFund = tokenHolderRevenueFund;
tokenHolderRevenueFund = newTokenHolderRevenueFund;
// Emit event
emit SetTokenHolderRevenueFundEvent(oldTokenHolderRevenueFund, newTokenHolderRevenueFund);
}
/// @notice Fallback function that deposits ethers to msg.sender's deposited balance
function()
external
payable
{
receiveEthersTo(msg.sender, balanceTracker.DEPOSITED_BALANCE_TYPE());
}
/// @notice Receive ethers to the given wallet's balance of the given type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type
function receiveEthersTo(address wallet, string memory balanceType)
public
payable
{
int256 value = SafeMathIntLib.toNonZeroInt256(msg.value);
// Register reception
_receiveTo(wallet, balanceType, value, address(0), 0, true);
// Emit event
emit ReceiveEvent(wallet, balanceType, value, address(0), 0, "");
}
/// @notice Receive token to msg.sender's balance of the given type
/// @dev The wallet must approve of this ClientFund's transfer prior to calling this function
/// @param balanceType The target balance type
/// @param value The value (amount of fungible, id of non-fungible) to receive
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 value, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, value, currencyCt, currencyId, standard);
}
/// @notice Receive token to the given wallet's balance of the given type
/// @dev The wallet must approve of this ClientFund's transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type
/// @param value The value (amount of fungible, id of non-fungible) to receive
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function receiveTokensTo(address wallet, string memory balanceType, int256 value, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(value.isNonZeroPositiveInt256());
// Get transfer controller
TransferController controller = transferController(currencyCt, standard);
// Execute transfer
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(value), currencyCt, currencyId
)
);
require(success);
// Register reception
_receiveTo(wallet, balanceType, value, currencyCt, currencyId, controller.isFungible());
// Emit event
emit ReceiveEvent(wallet, balanceType, value, currencyCt, currencyId, standard);
}
/// @notice Update the settled balance by the difference between provided off-chain balance amount
/// and deposited on-chain balance, where deposited balance is resolved at the given block number
/// @param wallet The address of the concerned wallet
/// @param value The target balance value (amount of fungible, id of non-fungible), i.e. off-chain balance
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
/// @param blockNumber The block number to which the settled balance is updated
function updateSettledBalance(address wallet, int256 value, address currencyCt, uint256 currencyId,
string memory standard, uint256 blockNumber)
public
onlyAuthorizedService(wallet)
notNullAddress(wallet)
{
require(value.isPositiveInt256());
if (_isFungible(currencyCt, currencyId, standard)) {
(int256 depositedValue,) = balanceTracker.fungibleRecordByBlockNumber(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId, blockNumber
);
balanceTracker.set(
wallet, balanceTracker.settledBalanceType(), value.sub(depositedValue),
currencyCt, currencyId, true
);
} else {
balanceTracker.sub(
wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, false
);
balanceTracker.add(
wallet, balanceTracker.settledBalanceType(), value, currencyCt, currencyId, false
);
}
// Emit event
emit UpdateSettledBalanceEvent(wallet, value, currencyCt, currencyId);
}
/// @notice Stage a value for subsequent withdrawal
/// @param wallet The address of the concerned wallet
/// @param value The value (amount of fungible, id of non-fungible) to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function stage(address wallet, int256 value, address currencyCt, uint256 currencyId,
string memory standard)
public
onlyAuthorizedService(wallet)
{
require(value.isNonZeroPositiveInt256());
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract stage value from settled, possibly also from deposited
value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible);
// Add to staged
balanceTracker.add(
wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible
);
// Emit event
emit StageEvent(wallet, value, currencyCt, currencyId, standard);
}
/// @notice Unstage a staged value
/// @param value The value (amount of fungible, id of non-fungible) to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function unstage(int256 value, address currencyCt, uint256 currencyId, string memory standard)
public
{
require(value.isNonZeroPositiveInt256());
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract unstage value from staged
value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible);
// Add to deposited
balanceTracker.add(
msg.sender, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible
);
// Emit event
emit UnstageEvent(msg.sender, value, currencyCt, currencyId, standard);
}
/// @notice Stage the value from wallet to the given beneficiary and targeted to wallet
/// @param wallet The address of the concerned wallet
/// @param beneficiary The (address of) concerned beneficiary contract
/// @param value The value (amount of fungible, id of non-fungible) to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function stageToBeneficiary(address wallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string memory standard)
public
onlyAuthorizedService(wallet)
{
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract stage value from settled, possibly also from deposited
value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible);
// Execute transfer
_transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard);
// Emit event
emit StageToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard);
}
/// @notice Transfer the given value of currency to the given beneficiary without target wallet
/// @param wallet The address of the concerned wallet
/// @param beneficiary The (address of) concerned beneficiary contract
/// @param value The value (amount of fungible, id of non-fungible) to transfer
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function transferToBeneficiary(address wallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string memory standard)
public
onlyAuthorizedService(wallet)
{
// Execute transfer
_transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard);
// Emit event
emit TransferToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard);
}
/// @notice Seize balances in the given currency of the given wallet, provided that the wallet
/// is locked by the caller
/// @param wallet The address of the concerned wallet whose balances are seized
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function seizeBalances(address wallet, address currencyCt, uint256 currencyId, string memory standard)
public
{
if (_isFungible(currencyCt, currencyId, standard))
_seizeFungibleBalances(wallet, msg.sender, currencyCt, currencyId);
else
_seizeNonFungibleBalances(wallet, msg.sender, currencyCt, currencyId);
// Add to the store of seized wallets
if (!seizedByWallet[wallet]) {
seizedByWallet[wallet] = true;
seizedWallets.push(wallet);
}
}
/// @notice Withdraw the given amount from staged balance
/// @param value The value (amount of fungible, id of non-fungible) to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 value, address currencyCt, uint256 currencyId, string memory standard)
public
{
require(value.isNonZeroPositiveInt256());
// Require that msg.sender and currency is not locked
require(!walletLocker.isLocked(msg.sender, currencyCt, currencyId));
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract unstage value from staged
value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible);
// Log record of this transaction
transactionTracker.add(
msg.sender, transactionTracker.withdrawalTransactionType(), value, currencyCt, currencyId
);
// Execute transfer
_transferToWallet(msg.sender, value, currencyCt, currencyId, standard);
// Emit event
emit WithdrawEvent(msg.sender, value, currencyCt, currencyId, standard);
}
/// @notice Get the seized status of given wallet
/// @param wallet The address of the concerned wallet
/// @return true if wallet is seized, false otherwise
function isSeizedWallet(address wallet)
public
view
returns (bool)
{
return seizedByWallet[wallet];
}
/// @notice Get the number of wallets whose funds have been seized
/// @return Number of wallets
function seizedWalletsCount()
public
view
returns (uint256)
{
return seizedWallets.length;
}
/// @notice Claim revenue from token holder revenue fund based on this contract's holdings of the
/// revenue token, this so that revenue may be shared amongst revenue token holders in nahmii
/// @param claimer The concerned address of claimer that will subsequently distribute revenue in nahmii
/// @param balanceType The target balance type for the reception in this contract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimRevenue(address claimer, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
onlyOperator
{
tokenHolderRevenueFund.claimAndTransferToBeneficiary(
this, claimer, balanceType,
currencyCt, currencyId, standard
);
emit ClaimRevenueEvent(claimer, balanceType, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _receiveTo(address wallet, string memory balanceType, int256 value, address currencyCt,
uint256 currencyId, bool fungible)
private
{
bytes32 balanceHash = 0 < bytes(balanceType).length ?
keccak256(abi.encodePacked(balanceType)) :
balanceTracker.depositedBalanceType();
// Add to per-wallet staged balance
if (balanceTracker.stagedBalanceType() == balanceHash)
balanceTracker.add(
wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible
);
// Add to per-wallet deposited balance
else if (balanceTracker.depositedBalanceType() == balanceHash) {
balanceTracker.add(
wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible
);
// Log record of this transaction
transactionTracker.add(
wallet, transactionTracker.depositTransactionType(), value, currencyCt, currencyId
);
}
else
revert();
}
function _subtractSequentially(address wallet, bytes32[] memory balanceTypes, int256 value, address currencyCt,
uint256 currencyId, bool fungible)
private
returns (int256)
{
if (fungible)
return _subtractFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId);
else
return _subtractNonFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId);
}
function _subtractFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 amount, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Require positive amount
require(0 <= amount);
uint256 i;
int256 totalBalanceAmount = 0;
for (i = 0; i < balanceTypes.length; i++)
totalBalanceAmount = totalBalanceAmount.add(
balanceTracker.get(
wallet, balanceTypes[i], currencyCt, currencyId
)
);
// Clamp amount to stage
amount = amount.clampMax(totalBalanceAmount);
int256 _amount = amount;
for (i = 0; i < balanceTypes.length; i++) {
int256 typeAmount = balanceTracker.get(
wallet, balanceTypes[i], currencyCt, currencyId
);
if (typeAmount >= _amount) {
balanceTracker.sub(
wallet, balanceTypes[i], _amount, currencyCt, currencyId, true
);
break;
} else {
balanceTracker.set(
wallet, balanceTypes[i], 0, currencyCt, currencyId, true
);
_amount = _amount.sub(typeAmount);
}
}
return amount;
}
function _subtractNonFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 id, address currencyCt, uint256 currencyId)
private
returns (int256)
{
for (uint256 i = 0; i < balanceTypes.length; i++)
if (balanceTracker.hasId(wallet, balanceTypes[i], id, currencyCt, currencyId)) {
balanceTracker.sub(wallet, balanceTypes[i], id, currencyCt, currencyId, false);
break;
}
return id;
}
function _subtractFromStaged(address wallet, int256 value, address currencyCt, uint256 currencyId, bool fungible)
private
returns (int256)
{
if (fungible) {
// Clamp value to unstage
value = value.clampMax(
balanceTracker.get(wallet, balanceTracker.stagedBalanceType(), currencyCt, currencyId)
);
// Require positive value
require(0 <= value);
} else {
// Require that value is included in staged balance
require(balanceTracker.hasId(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId));
}
// Subtract from deposited balance
balanceTracker.sub(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible);
return value;
}
function _transferToBeneficiary(address destWallet, Beneficiary beneficiary,
int256 value, address currencyCt, uint256 currencyId, string memory standard)
private
{
require(value.isNonZeroPositiveInt256());
require(isRegisteredBeneficiary(beneficiary));
// Transfer funds to the beneficiary
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(value))(destWallet, "");
else {
// Get transfer controller
TransferController controller = transferController(currencyCt, standard);
// Approve of beneficiary
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(value), currencyCt, currencyId
)
);
require(success);
// Transfer funds to the beneficiary
beneficiary.receiveTokensTo(destWallet, "", value, currencyCt, currencyId, controller.standard());
}
}
function _transferToWallet(address payable wallet,
int256 value, address currencyCt, uint256 currencyId, string memory standard)
private
{
// Transfer ETH
if (address(0) == currencyCt && 0 == currencyId)
wallet.transfer(uint256(value));
else {
// Get transfer controller
TransferController controller = transferController(currencyCt, standard);
// Transfer token
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), wallet, uint256(value), currencyCt, currencyId
)
);
require(success);
}
}
function _seizeFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt,
uint256 currencyId)
private
{
// Get the locked amount
int256 amount = walletLocker.lockedAmount(lockedWallet, lockerWallet, currencyCt, currencyId);
// Require that locked amount is strictly positive
require(amount > 0);
// Subtract stage value from settled, possibly also from deposited
_subtractFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), amount, currencyCt, currencyId);
// Add to staged balance of sender
balanceTracker.add(
lockerWallet, balanceTracker.stagedBalanceType(), amount, currencyCt, currencyId, true
);
// Emit event
emit SeizeBalancesEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
function _seizeNonFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt,
uint256 currencyId)
private
{
// Require that locked ids has entries
uint256 lockedIdsCount = walletLocker.lockedIdsCount(lockedWallet, lockerWallet, currencyCt, currencyId);
require(0 < lockedIdsCount);
// Get the locked amount
int256[] memory ids = walletLocker.lockedIdsByIndices(
lockedWallet, lockerWallet, currencyCt, currencyId, 0, lockedIdsCount - 1
);
for (uint256 i = 0; i < ids.length; i++) {
// Subtract from settled, possibly also from deposited
_subtractNonFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), ids[i], currencyCt, currencyId);
// Add to staged balance of sender
balanceTracker.add(
lockerWallet, balanceTracker.stagedBalanceType(), ids[i], currencyCt, currencyId, false
);
// Emit event
emit SeizeBalancesEvent(lockedWallet, lockerWallet, ids[i], currencyCt, currencyId);
}
}
function _isFungible(address currencyCt, uint256 currencyId, string memory standard)
private
view
returns (bool)
{
return (address(0) == currencyCt && 0 == currencyId) || transferController(currencyCt, standard).isFungible();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ClientFundable
* @notice An ownable that has a client fund property
*/
contract ClientFundable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
ClientFund public clientFund;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetClientFundEvent(ClientFund oldClientFund, ClientFund newClientFund);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the client fund contract
/// @param newClientFund The (address of) ClientFund contract instance
function setClientFund(ClientFund newClientFund) public
onlyDeployer
notNullAddress(address(newClientFund))
notSameAddresses(address(newClientFund), address(clientFund))
{
// Update field
ClientFund oldClientFund = clientFund;
clientFund = newClientFund;
// Emit event
emit SetClientFundEvent(oldClientFund, newClientFund);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier clientFundInitialized() {
require(address(clientFund) != address(0), "Client fund not initialized [ClientFundable.sol:51]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementState
* @notice Where null settlement state is managed
*/
contract NullSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public SET_MAX_NULL_NONCE_ACTION = "set_max_null_nonce";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxNullNonce;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetMaxNullNonceEvent(uint256 maxNullNonce);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event UpdateMaxNullNonceFromCommunityVoteEvent(uint256 maxNullNonce);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the max null nonce
/// @param _maxNullNonce The max nonce
function setMaxNullNonce(uint256 _maxNullNonce)
public
onlyEnabledServiceAction(SET_MAX_NULL_NONCE_ACTION)
{
// Update max nonce value
maxNullNonce = _maxNullNonce;
// Emit event
emit SetMaxNullNonceEvent(_maxNullNonce);
}
/// @notice Get the max null nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256) {
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max null nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param _maxNullNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 _maxNullNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = _maxNullNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, _maxNullNonce);
}
/// @notice Update the max null settlement nonce property from CommunityVote contract
function updateMaxNullNonceFromCommunityVote()
public
{
uint256 _maxNullNonce = communityVote.getMaxNullNonce();
if (0 == _maxNullNonce)
return;
maxNullNonce = _maxNullNonce;
// Emit event
emit UpdateMaxNullNonceFromCommunityVoteEvent(maxNullNonce);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlement
* @notice Where null settlement are finalized
*/
contract NullSettlement is Ownable, Configurable, ClientFundable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
NullSettlementState public nullSettlementState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetNullSettlementStateEvent(NullSettlementState oldNullSettlementState,
NullSettlementState newNullSettlementState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event SettleNullEvent(address wallet, address currencyCt, uint256 currencyId, string standard);
event SettleNullByProxyEvent(address proxy, address wallet, address currencyCt,
uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the null settlement state contract
/// @param newNullSettlementState The (address of) NullSettlementState contract instance
function setNullSettlementState(NullSettlementState newNullSettlementState)
public
onlyDeployer
notNullAddress(address(newNullSettlementState))
{
NullSettlementState oldNullSettlementState = nullSettlementState;
nullSettlementState = newNullSettlementState;
emit SetNullSettlementStateEvent(oldNullSettlementState, nullSettlementState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Settle null
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token to be settled (discarded if settling ETH)
function settleNull(address currencyCt, uint256 currencyId, string memory standard)
public
{
// Settle null
_settleNull(msg.sender, MonetaryTypesLib.Currency(currencyCt, currencyId), standard);
// Emit event
emit SettleNullEvent(msg.sender, currencyCt, currencyId, standard);
}
/// @notice Settle null by proxy
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token to be settled (discarded if settling ETH)
function settleNullByProxy(address wallet, address currencyCt, uint256 currencyId, string memory standard)
public
onlyOperator
{
// Settle null of wallet
_settleNull(wallet, MonetaryTypesLib.Currency(currencyCt, currencyId), standard);
// Emit event
emit SettleNullByProxyEvent(msg.sender, wallet, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _settleNull(address wallet, MonetaryTypesLib.Currency memory currency, string memory standard)
private
{
// Require that there is no overlapping driip settlement challenge
require(
!driipSettlementChallengeState.hasProposal(wallet, currency) ||
driipSettlementChallengeState.hasProposalTerminated(wallet, currency),
"Overlapping driip settlement challenge proposal found [NullSettlement.sol:136]"
);
// Require that null settlement challenge proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlement.sol:143]");
// Require that null settlement challenge proposal has not been terminated already
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlement.sol:146]");
// Require that null settlement challenge proposal has expired
require(nullSettlementChallengeState.hasProposalExpired(wallet, currency), "Proposal found not expired [NullSettlement.sol:149]");
// Require that null settlement challenge qualified
require(SettlementChallengeTypesLib.Status.Qualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
), "Proposal found not qualified [NullSettlement.sol:152]");
// Require that operational mode is normal and data is available, or that nonce is
// smaller than max null nonce
require(configuration.isOperationalModeNormal(), "Not normal operational mode [NullSettlement.sol:158]");
require(communityVote.isDataAvailable(), "Data not available [NullSettlement.sol:159]");
// Get null settlement challenge proposal nonce
uint256 nonce = nullSettlementChallengeState.proposalNonce(wallet, currency);
// If wallet has previously settled balance of the concerned currency with higher
// null settlement nonce, then don't settle again
require(nonce >= nullSettlementState.maxNonceByWalletAndCurrency(wallet, currency), "Nonce deemed smaller than max nonce by wallet and currency [NullSettlement.sol:166]");
// Update settled nonce of wallet and currency
nullSettlementState.setMaxNonceByWalletAndCurrency(wallet, currency, nonce);
// Stage the proposed amount
clientFund.stage(
wallet,
nullSettlementChallengeState.proposalStageAmount(
wallet, currency
),
currency.ct, currency.id, standard
);
// Remove null settlement challenge proposal
nullSettlementChallengeState.terminateProposal(wallet, currency);
}
} | Define a set of new releases earliestReleaseTimes The timestamp after which the corresponding amount may be released amounts The amounts to be released releaseBlockNumbers The set release block numbers for releases whose earliest release time is in the past Require that token address has been set Update the total amount locked by this contract Require that total amount locked is less than or equal to the token balance of this contract Retrieve early block number where available Add release Emit event | function defineReleases(uint256[] memory earliestReleaseTimes, uint256[] memory amounts, uint256[] memory releaseBlockNumbers)
onlyOperator
public
{
require(
earliestReleaseTimes.length == amounts.length,
"Earliest release times and amounts lengths mismatch [TokenMultiTimelock.sol:105]"
);
require(
earliestReleaseTimes.length >= releaseBlockNumbers.length,
"Earliest release times and release block numbers lengths mismatch [TokenMultiTimelock.sol:109]"
);
require(address(token) != address(0), "Token not initialized [TokenMultiTimelock.sol:115]");
for (uint256 i = 0; i < earliestReleaseTimes.length; i++) {
totalLockedAmount += amounts[i];
require(token.balanceOf(address(this)) >= totalLockedAmount, "Total locked amount overrun [TokenMultiTimelock.sol:123]");
uint256 blockNumber = i < releaseBlockNumbers.length ? releaseBlockNumbers[i] : 0;
releases.push(Release(earliestReleaseTimes[i], amounts[i], blockNumber, false));
emit DefineReleaseEvent(earliestReleaseTimes[i], amounts[i], blockNumber);
}
}
| 14,080,945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.