file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./full_match/137/0x947aC276763257c68c82cF30622BC4F4F804C027/sources/contracts/Wallet.sol
|
amountIn should be in terms of the token from which we are swapping
|
function swapExactInputSingle(address _returnBaseToken, address _tokenIn, uint256 _amountIn)
internal
returns (uint256 amountOut)
{
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
.ExactInputSingleParams({
tokenIn: _tokenIn,
tokenOut: _returnBaseToken,
fee: poolFee,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
amountOut = swapRouter.exactInputSingle(params);
return amountOut;
}
| 3,751,335
|
pragma solidity >=0.5.4 <0.6.0;
interface tokenRecipient { function RECEIVEAPPROVAL172(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } //inject NONSTANDARD NAMING
library SafeMath {
function MUL710(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function DIV595(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function SUB853(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD540(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
assert(c >= a);
return c;
}
}
interface INameTAOPosition {
function SENDERISADVOCATE978(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISLISTENER841(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISSPEAKER648(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISPOSITION99(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function GETADVOCATE521(address _id) external view returns (address); //inject NONSTANDARD NAMING
function NAMEISADVOCATE881(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function NAMEISPOSITION327(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function INITIALIZE405(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool); //inject NONSTANDARD NAMING
function DETERMINEPOSITION456(address _sender, address _id) external view returns (uint256); //inject NONSTANDARD NAMING
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
// This generates a public event on the blockchain that will notify clients
event APPROVAL454(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING
// This notifies clients about the amount burnt
event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor (uint256 initialSupply, string memory tokenName, string memory 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
}
function _TRANSFER285(address _from, address _to, uint _value) internal { //inject NONSTANDARD NAMING
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// 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 TRANSFER193(_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 TRANSFER874(address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
_TRANSFER285(msg.sender, _to, _value);
return true;
}
function TRANSFERFROM282(address _from, address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_TRANSFER285(_from, _to, _value);
return true;
}
function APPROVE265(address _spender, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
allowance[msg.sender][_spender] = _value;
emit APPROVAL454(msg.sender, _spender, _value);
return true;
}
function APPROVEANDCALL88(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { //inject NONSTANDARD NAMING
tokenRecipient spender = tokenRecipient(_spender);
if (APPROVE265(_spender, _value)) {
spender.RECEIVEAPPROVAL172(msg.sender, _value, address(this), _extraData);
return true;
}
}
function BURN239(uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit BURN994(msg.sender, _value);
return true;
}
function BURNFROM882(address _from, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
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 BURN994(_from, _value);
return true;
}
}
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
uint8 public typeId;
constructor (string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
modifier ONLYVAULT404 { //inject NONSTANDARD NAMING
require (msg.sender == vaultAddress);
_;
}
function () external payable {
}
function TRANSFERETH144(address payable _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING
_recipient.transfer(_amount);
return true;
}
function TRANSFERERC20563(address _erc20TokenAddress, address _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.TRANSFER874(_recipient, _amount);
return true;
}
}
contract Name is TAO {
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _multiplier_divisor322 = 10 ** 6; // 1000000 = 1 //inject NONSTANDARD NAMING
uint256 constant private _percentage_divisor262 = 10 ** 6; // 100% = 1000000 //inject NONSTANDARD NAMING
function ISTAO231(address _taoId) public view returns (bool) { //inject NONSTANDARD NAMING
return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0);
}
function ISNAME781(address _nameId) public view returns (bool) { //inject NONSTANDARD NAMING
return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1);
}
function ISVALIDERC20TOKENADDRESS312(address _tokenAddress) public view returns (bool) { //inject NONSTANDARD NAMING
if (_tokenAddress == address(0)) {
return false;
}
TokenERC20 _erc20 = TokenERC20(_tokenAddress);
return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
}
function ISTHEAO403(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { //inject NONSTANDARD NAMING
return (_sender == _theAO ||
(
(ISTAO231(_theAO) || ISNAME781(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
INameTAOPosition(_nameTAOPositionAddress).SENDERISADVOCATE978(_sender, _theAO)
)
);
}
function PERCENTAGE_DIVISOR218() public pure returns (uint256) { //inject NONSTANDARD NAMING
return _percentage_divisor262;
}
function MULTIPLIER_DIVISOR371() public pure returns (uint256) { //inject NONSTANDARD NAMING
return _multiplier_divisor322;
}
function DEPLOYTAO162(string memory _name, //inject NONSTANDARD NAMING
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (TAO _tao) {
_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function DEPLOYNAME486(string memory _name, //inject NONSTANDARD NAMING
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (Name _myName) {
_myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function CALCULATEWEIGHTEDMULTIPLIER712(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedIons = (_currentWeightedMultiplier.MUL710(_currentPrimordialBalance)).ADD540(_additionalWeightedMultiplier.MUL710(_additionalPrimordialAmount));
uint256 _totalIons = _currentPrimordialBalance.ADD540(_additionalPrimordialAmount);
return _totalWeightedIons.DIV595(_totalIons);
} else {
return _additionalWeightedMultiplier;
}
}
function CALCULATEPRIMORDIALMULTIPLIER760(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2));
uint256 multiplier = (_multiplier_divisor322.SUB853(_multiplier_divisor322.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier));
return multiplier.DIV595(_multiplier_divisor322);
} else {
return 0;
}
}
function CALCULATENETWORKBONUSPERCENTAGE146(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2));
uint256 bonusPercentage = (_percentage_divisor262.SUB853(_percentage_divisor262.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier)).DIV595(_percentage_divisor262);
return bonusPercentage;
} else {
return 0;
}
}
function CALCULATENETWORKBONUSAMOUNT621(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 bonusPercentage = CALCULATENETWORKBONUSPERCENTAGE146(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
uint256 networkBonus = bonusPercentage.MUL710(_purchaseAmount).DIV595(_percentage_divisor262);
return networkBonus;
}
function CALCULATEMAXIMUMBURNAMOUNT319(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
return (_maximumMultiplier.MUL710(_primordialBalance).SUB853(_primordialBalance.MUL710(_currentWeightedMultiplier))).DIV595(_maximumMultiplier);
}
function CALCULATEMULTIPLIERAFTERBURN888(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { //inject NONSTANDARD NAMING
return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.SUB853(_amountToBurn));
}
function CALCULATEMULTIPLIERAFTERCONVERSION91(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { //inject NONSTANDARD NAMING
return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.ADD540(_amountToConvert));
}
function NUMDIGITS612(uint256 number) public pure returns (uint8) { //inject NONSTANDARD NAMING
uint8 digits = 0;
while(number != 0) {
number = number.DIV595(10);
digits++;
}
return digits;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
modifier INWHITELIST24() { //inject NONSTANDARD NAMING
require (whitelist[msg.sender] == true);
_;
}
function TRANSFEROWNERSHIP920(address _theAO) public { //inject NONSTANDARD NAMING
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
function SETWHITELIST120(address _account, bool _whitelist) public { //inject NONSTANDARD NAMING
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the contract
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor (string memory _name, string memory _symbol, address _nameTAOPositionAddress) public {
name = _name; // Set the name for display purposes
symbol = _symbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
SETNAMETAOPOSITIONADDRESS170(_nameTAOPositionAddress);
}
modifier ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (AOLibrary.ISTHEAO403(msg.sender, theAO, nameTAOPositionAddress));
_;
}
modifier ISNAMEORTAO154(address _id) { //inject NONSTANDARD NAMING
require (AOLibrary.ISNAME781(_id) || AOLibrary.ISTAO231(_id));
_;
}
function TRANSFEROWNERSHIP920(address _theAO) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_theAO != address(0));
theAO = _theAO;
}
function SETWHITELIST120(address _account, bool _whitelist) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_account != address(0));
whitelist[_account] = _whitelist;
}
function SETNAMETAOPOSITIONADDRESS170(address _nameTAOPositionAddress) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
function TRANSFERFROM282(address _from, address _to, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) ISNAMEORTAO154(_to) returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER285(_from, _to, _value);
return true;
}
function MINT678(address target, uint256 mintedAmount) public INWHITELIST24 ISNAMEORTAO154(target) returns (bool) { //inject NONSTANDARD NAMING
_MINT887(target, mintedAmount);
return true;
}
function WHITELISTBURNFROM289(address _from, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the targeted balance
totalSupply = totalSupply.SUB853(_value); // Update totalSupply
emit BURN994(_from, _value);
return true;
}
function _TRANSFER285(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].ADD540(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].ADD540(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].ADD540(_value); // Add the same to the recipient
emit TRANSFER193(_from, _to, _value);
assert(balanceOf[_from].ADD540(balanceOf[_to]) == previousBalances);
}
function _MINT887(address target, uint256 mintedAmount) internal { //inject NONSTANDARD NAMING
balanceOf[target] = balanceOf[target].ADD540(mintedAmount);
totalSupply = totalSupply.ADD540(mintedAmount);
emit TRANSFER193(address(0), address(this), mintedAmount);
emit TRANSFER193(address(this), target, mintedAmount);
}
}
contract PathosGiga is TAOCurrency {
constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress)
TAOCurrency(_name, _symbol, _nameTAOPositionAddress) public {
powerOfTen = 9;
decimals = 9;
}
}
|
inject NONSTANDARD NAMING
|
function TRANSFERETH144(address payable _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) {
| 13,026,367
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol';
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
interface IJoeTraderRouter02 {
function addLiquidityAVAX(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountAVAXMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountAVAX, uint liquidity);
function swapExactTokensForAVAXSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function WAVAX() external pure returns (address);
}
contract JPEGvaultDAOTokenV3AVAX is ERC20SnapshotUpgradeable, OwnableUpgradeable {
//
// Don't touch this if you want to upgrade - BEGIN
//
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
EnumerableSetUpgradeable.AddressSet private excludedRedistribution; // exclure de la redistribution
mapping(address => bool) private excludedTax;
IJoeTraderRouter02 private dexRouter;
address private uniswapV2Pair;
address private WAVAXAddr;
address private growthAddress; // Should no longer be used since v3
address private vaultAddress; // Should no longer be used since v3
address private liquidityAddress; // Should no longer be used since v3
address private redistributionContract;
uint8 private growthFees; // Should no longer be used since v3
uint8 private vaultFees; // Should no longer be used since v3
uint8 private liquidityFees; // Should no longer be used since v3
uint8 private autoLiquidityFees;
// Autoselling ratio between 0 and 100
uint8 private autoSellingRatio;
uint216 private minAmountForSwap;
// Stores tokens waiting for the next swap
uint private autoSellGrowthStack;
uint private autoSellVaultStack;
uint private autoSellLiquidityStack;
//
// Don't touch this if you want to upgrade - END
//
// v3
uint8 public purchaseTax;
uint8 public sellTax;
uint8 public walletTax;
address private treasuryAddress;
uint16 public minimumBlockDelay;
bool private migrated2v3;
address private bridgeAddress;
uint private autoSellStack;
mapping(address => uint256) private lastTransfer;
function initialize(address _growthAddress,
address _router) external initializer {
__Ownable_init();
__ERC20_init("JPEG", "JPEG");
__ERC20Snapshot_init();
dexRouter = IJoeTraderRouter02(_router);
WAVAXAddr = dexRouter.WAVAX();
growthAddress = _growthAddress;
_transferOwnership(growthAddress);
excludedRedistribution.add(address(this));
excludedRedistribution.add(growthAddress);
excludedTax[address(this)] = true;
excludedTax[growthAddress] = true;
purchaseTax = 10;
sellTax = 10;
walletTax = 10;
treasuryAddress = 0x73d6F7de9e9Ba999088B691b72b7291e7738e0eD;
excludedTax[treasuryAddress] = true;
minAmountForSwap = 1_000;
migrated2v3 = true;
_mint(growthAddress, 1_000_000_000 * 10 ** 18);
}
receive() external payable {}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (!excludedTax[sender] &&
!excludedTax[recipient]) {
if (recipient == uniswapV2Pair) {
amount = applyTaxes(sender, amount, sellTax);
checkLastTransfer(sender);
}
else if (sender == uniswapV2Pair) {
amount = applyTaxes(sender, amount, purchaseTax);
checkLastTransfer(recipient);
}
else {
amount = applyTaxes(sender, amount, walletTax);
}
}
super._transfer(sender, recipient, amount);
}
function checkLastTransfer(address trader) internal {
if (minimumBlockDelay > 0) {
require ((block.number - lastTransfer[trader]) >= minimumBlockDelay,
"Transfer too close from previous one");
lastTransfer[trader] = block.number;
}
}
function applyTaxes(address sender, uint amount, uint8 tax) internal returns (uint newAmountTransfer) {
uint amountTax = amount * tax;
uint amountAutoLiquidity = amount * autoLiquidityFees;
// Cheaper without "no division by 0" check
unchecked {
amountTax /= 100;
amountAutoLiquidity /= 100;
}
newAmountTransfer = amount
- amountTax
- amountAutoLiquidity;
// Apply autoselling ratio
uint autoSell = amountTax * autoSellingRatio;
// Cheaper without "no division by 0" check
unchecked {
autoSell /= 100;
}
// Transfer the remaining tokens to wallets
super._transfer(sender, treasuryAddress, amountTax - autoSell);
// Transfer all autoselling + autoLP to the contract
super._transfer(sender, address(this), autoSell
+ amountAutoLiquidity);
uint tokenBalance = balanceOf(address(this));
// Only swap if it's worth it
if (tokenBalance >= (minAmountForSwap * 1 ether)
&& uniswapV2Pair != address(0)
&& uniswapV2Pair != msg.sender) {
swapAndLiquify(tokenBalance,
autoSell);
} else {
// Stack tokens to be swapped for autoselling
autoSellStack = autoSellStack + autoSell;
}
}
function swapAndLiquify(uint tokenBalance,
uint autoSell) internal {
uint finalAutoSell = autoSellStack + autoSell;
uint amountToLiquifiy = tokenBalance - finalAutoSell;
// Stack tokens for autoliquidity pool
uint tokensToBeSwappedForLP;
unchecked {
tokensToBeSwappedForLP = amountToLiquifiy / 2;
}
uint tokensForLP = amountToLiquifiy - tokensToBeSwappedForLP;
uint totalToSwap = finalAutoSell + tokensToBeSwappedForLP;
// Swap all in one call
uint balanceInAVAX = address(this).balance;
swapTokensForAVAX(totalToSwap);
uint totalAVAXswaped = address(this).balance - balanceInAVAX;
// Redistribute according to weigth
uint autosellAVAX = totalAVAXswaped * finalAutoSell / totalToSwap;
AddressUpgradeable.sendValue(payable(treasuryAddress), autosellAVAX);
uint availableAVAXForLP = totalAVAXswaped - autosellAVAX;
addLiquidity(tokensForLP, availableAVAXForLP);
autoSellStack = 0;
}
function addLiquidity(uint tokenAmount, uint avaxAmount) internal {
if (tokenAmount >0) {
// add liquidity with token and AVAX
_approve(address(this), address(dexRouter), tokenAmount);
dexRouter.addLiquidityAVAX{value: avaxAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
}
function swapTokensForAVAX(uint256 amount) private {
address[] memory _path = new address[](2);
_path[0] = address(this);
_path[1] = address(WAVAXAddr);
_approve(address(this), address(dexRouter), amount);
dexRouter.swapExactTokensForAVAXSupportingFeeOnTransferTokens(
amount,
0,
_path,
address(this),
block.timestamp
);
}
function createRedistribution() public returns (uint, uint) {
require(msg.sender == redistributionContract, "Bad caller");
uint newSnapshotId = _snapshot();
return (newSnapshotId, calcSupplyHolders());
}
function calcSupplyHolders() internal view returns (uint) {
uint balanceExcluded = 0;
for (uint i = 0; i < excludedRedistribution.length(); i++)
balanceExcluded += balanceOf(excludedRedistribution.at(i));
return totalSupply() - balanceExcluded;
}
function setMinimumBlockDelay(uint16 blockCount) external onlyOwner {
minimumBlockDelay = blockCount;
}
function setPurchaseTax(uint8 _tax) external onlyOwner {
purchaseTax = _tax;
}
function setSellTax(uint8 _tax) external onlyOwner {
sellTax = _tax;
}
function setWalletTax(uint8 _tax) external onlyOwner {
walletTax = _tax;
}
function setTreasuryAddress(address _address) external onlyOwner {
treasuryAddress = _address;
excludedTax[_address] = true;
}
function setBridgeAddress(address _address) external onlyOwner {
bridgeAddress = _address;
excludedTax[_address] = true;
}
function excludeTaxAddress(address _address) external onlyOwner {
excludedTax[_address] = true;
}
function removeTaxAddress(address _address) external onlyOwner {
require(_address != address(this), "Not authorized to remove the contract from tax");
excludedTax[_address] = false;
}
// Bridging feature
function mint(address to, uint256 amount) external {
require(msg.sender == bridgeAddress, "Only bridge can mint");
_mint(to, amount);
}
function burn(address to, uint256 amount) external {
require(msg.sender == bridgeAddress, "Only bridge can mint");
_burn(to, amount);
}
// Liquidity settings
function setAutoLiquidityFees(uint8 _fees) external onlyOwner {
autoLiquidityFees = _fees;
}
function setMinAmountForSwap(uint216 _amount) external onlyOwner {
minAmountForSwap = _amount;
}
function setUniswapV2Pair(address _pair) external onlyOwner {
uniswapV2Pair = _pair;
excludedRedistribution.add(_pair);
}
function setAutoSellingRatio(uint8 ratio) external onlyOwner{
require(autoSellingRatio <= 100, "autoSellingRatio should be lower than 100");
autoSellingRatio = ratio;
}
// Redistribution management
function setRedistributionContract(address _address) external onlyOwner {
redistributionContract = _address;
excludedRedistribution.add(_address);
excludedTax[_address] =true;
}
function removeRedistributionAddress(address _address) external onlyOwner {
excludedRedistribution.remove(_address);
}
function excludedRedistributionAddress(address _address) external onlyOwner {
excludedRedistribution.add(_address);
}
}
|
Cheaper without "no division by 0" check Cheaper without "no division by 0" check Stack tokens to be swapped for autoselling
|
function applyTaxes(address sender, uint amount, uint8 tax) internal returns (uint newAmountTransfer) {
uint amountTax = amount * tax;
uint amountAutoLiquidity = amount * autoLiquidityFees;
unchecked {
amountTax /= 100;
amountAutoLiquidity /= 100;
}
newAmountTransfer = amount
- amountTax
- amountAutoLiquidity;
unchecked {
autoSell /= 100;
}
+ amountAutoLiquidity);
uint tokenBalance = balanceOf(address(this));
&& uniswapV2Pair != address(0)
&& uniswapV2Pair != msg.sender) {
swapAndLiquify(tokenBalance,
autoSell);
autoSellStack = autoSellStack + autoSell;
}
}
| 5,382,519
|
// File: contracts/ComptrollerInterface.sol
pragma solidity 0.5.17;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
// File: contracts/InterestRateModel.sol
pragma solidity 0.5.17;
/**
* @title InterestRateModel Interface
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// File: contracts/GTokenInterfaces.sol
pragma solidity 0.5.17;
contract GTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-gToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract GTokenInterface is GTokenStorage {
/**
* @notice Indicator that this is a GToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
// File: contracts/ErrorReporter.sol
pragma solidity 0.5.17;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR, // 0
UNAUTHORIZED, // 1
COMPTROLLER_MISMATCH, // 2
INSUFFICIENT_SHORTFALL, // 3
INSUFFICIENT_LIQUIDITY, // 4
INVALID_CLOSE_FACTOR, // 5
INVALID_COLLATERAL_FACTOR, // 6
INVALID_LIQUIDATION_INCENTIVE, // 7
MARKET_NOT_ENTERED, // 8 no longer possible
MARKET_NOT_LISTED, // 9
MARKET_ALREADY_LISTED, // 10
MATH_ERROR, // 11
NONZERO_BORROW_BALANCE, // 12
PRICE_ERROR, // 13
REJECTION, // 14
SNAPSHOT_ERROR, // 15
TOO_MANY_ASSETS, // 16
TOO_MUCH_REPAY // 17
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, // 1
EXIT_MARKET_BALANCE_OWED, // 2
EXIT_MARKET_REJECTION, // 3
SET_CLOSE_FACTOR_OWNER_CHECK, // 4
SET_CLOSE_FACTOR_VALIDATION, // 5
SET_COLLATERAL_FACTOR_OWNER_CHECK, // 6
SET_COLLATERAL_FACTOR_NO_EXISTS, // 7
SET_COLLATERAL_FACTOR_VALIDATION, // 8
SET_COLLATERAL_FACTOR_WITHOUT_PRICE, // 9
SET_IMPLEMENTATION_OWNER_CHECK, // 10
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, // 11
SET_LIQUIDATION_INCENTIVE_VALIDATION, // 12
SET_MAX_ASSETS_OWNER_CHECK, // 13
SET_PENDING_ADMIN_OWNER_CHECK, // 14
SET_PENDING_IMPLEMENTATION_OWNER_CHECK, // 15
SET_PRICE_ORACLE_OWNER_CHECK, // 16
SUPPORT_MARKET_EXISTS, // 17
SUPPORT_MARKET_OWNER_CHECK, // 18
SET_PAUSE_GUARDIAN_OWNER_CHECK // 19
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR, // 0
UNAUTHORIZED, // 1
BAD_INPUT, // 2
COMPTROLLER_REJECTION, // 3
COMPTROLLER_CALCULATION_ERROR, // 4
INTEREST_RATE_MODEL_ERROR, // 5
INVALID_ACCOUNT_PAIR, // 6
INVALID_CLOSE_AMOUNT_REQUESTED, // 7
INVALID_COLLATERAL_FACTOR, // 8
MATH_ERROR, // 9
MARKET_NOT_FRESH, // 10
MARKET_NOT_LISTED, // 11
TOKEN_INSUFFICIENT_ALLOWANCE, // 12
TOKEN_INSUFFICIENT_BALANCE, // 13
TOKEN_INSUFFICIENT_CASH, // 14
TOKEN_TRANSFER_IN_FAILED, // 15
TOKEN_TRANSFER_OUT_FAILED // 16
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, // 1
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, // 2
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, // 3
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, // 4
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, // 5
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, // 6
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, // 7
BORROW_ACCRUE_INTEREST_FAILED, // 8
BORROW_CASH_NOT_AVAILABLE, // 9
BORROW_FRESHNESS_CHECK, // 10
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 11
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, // 12
BORROW_MARKET_NOT_LISTED, // 13
BORROW_COMPTROLLER_REJECTION, // 14
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, // 15
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, // 16
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, // 17
LIQUIDATE_COMPTROLLER_REJECTION, // 18
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, // 19
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, // 20
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, // 21
LIQUIDATE_FRESHNESS_CHECK, // 22
LIQUIDATE_LIQUIDATOR_IS_BORROWER, // 23
LIQUIDATE_REPAY_BORROW_FRESH_FAILED, // 24
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, // 25
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, // 26
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, // 27
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, // 28
LIQUIDATE_SEIZE_TOO_MUCH, // 29
MINT_ACCRUE_INTEREST_FAILED, // 30
MINT_COMPTROLLER_REJECTION, // 31
MINT_EXCHANGE_CALCULATION_FAILED, // 32
MINT_EXCHANGE_RATE_READ_FAILED, // 33
MINT_FRESHNESS_CHECK, // 34
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 35
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 36
MINT_TRANSFER_IN_FAILED, // 37
MINT_TRANSFER_IN_NOT_POSSIBLE, // 38
REDEEM_ACCRUE_INTEREST_FAILED, // 39
REDEEM_COMPTROLLER_REJECTION, // 40
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, // 41
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, // 42
REDEEM_EXCHANGE_RATE_READ_FAILED, // 42
REDEEM_FRESHNESS_CHECK, // 43
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 44
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 45
REDEEM_TRANSFER_OUT_NOT_POSSIBLE, // 46
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, // 47
REDUCE_RESERVES_ADMIN_CHECK, // 48
REDUCE_RESERVES_CASH_NOT_AVAILABLE, // 49
REDUCE_RESERVES_FRESH_CHECK, // 50
REDUCE_RESERVES_VALIDATION, // 51
REPAY_BEHALF_ACCRUE_INTEREST_FAILED, // 52
REPAY_BORROW_ACCRUE_INTEREST_FAILED, // 53
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, //54
REPAY_BORROW_COMPTROLLER_REJECTION, // 55
REPAY_BORROW_FRESHNESS_CHECK, // 56
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, //57
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 58
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, // 59
SET_COLLATERAL_FACTOR_OWNER_CHECK, // 60
SET_COLLATERAL_FACTOR_VALIDATION, // 61
SET_COMPTROLLER_OWNER_CHECK, // 62
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, //63
SET_INTEREST_RATE_MODEL_FRESH_CHECK, // 64
SET_INTEREST_RATE_MODEL_OWNER_CHECK, // 65
SET_MAX_ASSETS_OWNER_CHECK, // 66
SET_ORACLE_MARKET_NOT_LISTED, // 67
SET_PENDING_ADMIN_OWNER_CHECK, // 68
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, // 69
SET_RESERVE_FACTOR_ADMIN_CHECK, // 70
SET_RESERVE_FACTOR_FRESH_CHECK, // 71
SET_RESERVE_FACTOR_BOUNDS_CHECK, // 72
TRANSFER_COMPTROLLER_REJECTION, // 73
TRANSFER_NOT_ALLOWED, // 74
TRANSFER_NOT_ENOUGH, // 75
TRANSFER_TOO_MUCH, // 76
ADD_RESERVES_ACCRUE_INTEREST_FAILED, // 77
ADD_RESERVES_FRESH_CHECK, // 78
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE // 79
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// File: contracts/CarefulMath.sol
pragma solidity 0.5.17;
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// File: contracts/Exponential.sol
pragma solidity 0.5.17;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: contracts/EIP20Interface.sol
pragma solidity 0.5.17;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/EIP20NonStandardInterface.sol
pragma solidity 0.5.17;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/GToken.sol
pragma solidity 0.5.17;
/**
* @title GToken Contract
* @notice Abstract base for CTokens
*/
contract GToken is GTokenInterface, Exponential, TokenErrorReporter {
bytes32 internal constant projectHash = keccak256(abi.encodePacked("ZILD"));
/**
* @notice Underlying asset for this GToken
*/
address public underlying;
/**
* @notice , ETH is native coin
*/
bool public underlyingIsNativeCoin;
// borrow fee amount * borrowFee / 10000;
uint public borrowFee;
// redeem fee amount = redeem amount * redeemFee / 10000;
uint public redeemFee;
uint public constant TEN_THOUSAND = 10000;
// max fee borrow redeem fee : 1%
uint public constant MAX_BORROW_REDEEM_FEE = 100;
// borrow fee and redeemFee will send to feeTo
address payable public feeTo;
event NewBorrowFee(uint oldBorrowFee, uint newBorrowFee);
event NewRedeemFee(uint oldRedeemFee, uint newRedeemFee);
event NewFeeTo(address oldFeeTo, address newFeeTo);
/**
* @notice Initialize the money market
* @param underlying_ Underlying asset for this GToken, ZETH's underlying is address(0)
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
* @param borrowFee_ borrow fee
* @param redeemFee_ redeem fee
* @param feeTo_ fee address
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_, uint borrowFee_, uint redeemFee_, address payable feeTo_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
_setBorrowFee(borrowFee_);
_setRedeemFee(redeemFee_);
_setFeeTo(feeTo_);
name = name_;
symbol = symbol_;
decimals = decimals_;
underlying = underlying_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice .
* @dev Admin function: change borrowFee.
* @param newBorrowFee newBorrowFee
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBorrowFee(uint newBorrowFee) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newBorrowFee <= MAX_BORROW_REDEEM_FEE, "newBorrowFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(borrowFee, newBorrowFee);
borrowFee = newBorrowFee;
return uint(Error.NO_ERROR);
}
/**
* @notice .
* @dev Admin function: change redeemFee.
* @param newRedeemFee newRedeemFee
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRedeemFee(uint newRedeemFee) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newRedeemFee <= MAX_BORROW_REDEEM_FEE, "newRedeemFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(redeemFee, newRedeemFee);
redeemFee = newRedeemFee;
return uint(Error.NO_ERROR);
}
/**
* @notice .
* @dev Admin function: change feeTo.
* @param newFeeTo newFeeTo
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setFeeTo(address payable newFeeTo) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newFeeTo != address(0), "newFeeTo is zero address");
emit NewFeeTo(feeTo, newFeeTo);
feeTo = newFeeTo;
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this gToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this gToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the GToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the GToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this gToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the gToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint fee = 0;
uint redeemAmountMinusFee = 0;
(vars.mathErr, fee) = mulUInt(vars.redeemAmount, redeemFee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, redeemAmountMinusFee) = subUInt(vars.redeemAmount, fee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
// doTransferOut(redeemer, vars.redeemAmount);
// vars.redeemAmount = redeemAmountMinusFee + fee
doTransferOut(redeemer, redeemAmountMinusFee);
doTransferOut(feeTo, fee);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint fee = 0;
uint borrowAmountMinusFee = 0;
(vars.mathErr, fee) = mulUInt(borrowAmount, borrowFee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, borrowAmountMinusFee) = subUInt(borrowAmount, fee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
doTransferOut(borrower, borrowAmountMinusFee);
doTransferOut(feeTo, fee);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this gToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this gToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another gToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed gToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another GToken.
* Its absolutely critical to use msg.sender as the seizer gToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed gToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// File: contracts/PriceOracle.sol
pragma solidity 0.5.17;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a gToken asset
* @param gToken The gToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(GToken gToken) external view returns (uint);
/**
* Get underlying market price for web app
*/
function getMarketPrice(string calldata symbol) external view returns (uint);
/**
* Get underlying oracle price for web app
*/
function price(string calldata symbol) external view returns (uint);
}
// File: contracts/ComptrollerStorage.sol
pragma solidity 0.5.17;
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Supervisor
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Supervisor
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => GToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
/// @notice A list of all markets
GToken[] public allMarkets;
}
// File: contracts/Comptroller.sol
pragma solidity 0.5.17;
/**
* @title Comptroller Contract
*/
contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(GToken gToken);
/// @notice Emitted when an account enters a market
event MarketEntered(GToken gToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(GToken gToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(GToken gToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionGlobalPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionMarketPaused(GToken gToken, string action, bool pauseState);
/// @notice Emitted when market comped status is changed
event MarketComped(GToken gToken, bool isComped);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (GToken[] memory) {
GToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param gToken The gToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, GToken gToken) external view returns (bool) {
return markets[address(gToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param gTokens The list of addresses of the gToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory gTokens) public returns (uint[] memory) {
uint len = gTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
GToken gToken = GToken(gTokens[i]);
results[i] = uint(addToMarketInternal(gToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param gToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(GToken gToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(gToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(gToken);
emit MarketEntered(gToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param gTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address gTokenAddress) external returns (uint) {
GToken gToken = GToken(gTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the gToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = gToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(gTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(gToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set gToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete gToken from the account’s list of assets */
// load into memory for faster iteration
GToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == gToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
GToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(gToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param gToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address gToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[gToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param gToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address gToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
gToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param gToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of gTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address gToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(gToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address gToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[gToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, GToken(gToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param gToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address gToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
gToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param gToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address gToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[gToken], "borrow is paused");
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[gToken].accountMembership[borrower]) {
// only gTokens may call borrowAllowed if borrower not in market
require(msg.sender == gToken, "sender must be gToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(GToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[gToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(GToken(gToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, GToken(gToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param gToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address gToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
gToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param gToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address gToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param gToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address gToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
gToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address gTokenBorrowed,
address gTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[gTokenBorrowed].isListed || !markets[gTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = GToken(gTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address gTokenBorrowed,
address gTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
gTokenBorrowed;
gTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address gTokenCollateral,
address gTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[gTokenCollateral].isListed || !markets[gTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (GToken(gTokenCollateral).comptroller() != GToken(gTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address gTokenCollateral,
address gTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
gTokenCollateral;
gTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param gToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of gTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address gToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(gToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param gToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of gTokens to transfer
*/
function transferVerify(address gToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
gToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `gTokenBalance` is the number of gTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint gTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param gTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address gTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(gTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param gTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral gToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
GToken gTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
GToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
GToken asset = assets[i];
// Read the balances and exchange rate from the gToken
(oErr, vars.gTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * gTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.gTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with gTokenModify
if (asset == gTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in gToken.liquidateBorrowFresh)
* @param gTokenBorrowed The address of the borrowed gToken
* @param gTokenCollateral The address of the collateral gToken
* @param actualRepayAmount The amount of gTokenBorrowed underlying to convert into gTokenCollateral tokens
* @return (errorCode, number of gTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address gTokenBorrowed, address gTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(GToken(gTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(GToken(gTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param gToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(GToken gToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(gToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(gToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(gToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param gToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(GToken gToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(gToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
gToken.isCToken(); // Sanity check to make sure its really a GToken
markets[address(gToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0});
_addMarketInternal(address(gToken));
emit MarketListed(gToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address gToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != GToken(gToken), "market already added");
}
allMarkets.push(GToken(gToken));
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(GToken gToken, bool state) public returns (bool) {
require(markets[address(gToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(gToken)] = state;
emit ActionMarketPaused(gToken, "Mint", state);
return state;
}
function _setBorrowPaused(GToken gToken, bool state) public returns (bool) {
require(markets[address(gToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(gToken)] = state;
emit ActionMarketPaused(gToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionGlobalPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionGlobalPaused("Seize", state);
return state;
}
/*
function _become(Supervisor unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
*/
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (GToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
|
If the redeemer is not 'in' the market, then we can bypass the liquidity check /
|
function redeemAllowedInternal(address gToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[gToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
| 598,555
|
./partial_match/1/0x08E1451D4f34cD67E9b4647bCcb251483EeeC6D7/sources/MultiSigStub.sol
|
ERC23 Token fallback _from address incoming token _amount incoming amount/
|
function tokenFallback(address _from, uint _amount, bytes _data)
public
{
_deposited(_from, _amount, msg.sender, _data);
}
| 9,309,977
|
./partial_match/3/0xfAb28Aac8A4b70de52E1cDcc9858360aBB8e6B37/sources/Dice.sol
|
Check Game Players Balance Initialize the balance of players Emit events of this game
|
function playDiceGame(
address[] memory playerList,
uint256[] memory playerScoreList,
uint256 playAmount,
uint256 gameLength
) public payable onlyOwner returns (bool) {
for (uint256 i = 0; i < gameLength; i++) {
require(
_playerETHBalance[playerList[i]] >= playAmount,
"The balance of all players should be more than playAmount."
);
}
for (uint256 i = 1; i < gameLength; i++) {
if (playerScoreList[winnerId] < playerScoreList[i]) {
winnerId = i;
}
}
uint256 winnerAmount = totalGameAmount.mul(_winnerPercent).div(10000);
uint256 feeAmount = totalGameAmount.sub(winnerAmount);
_totalFeeAmount = _totalFeeAmount.add(feeAmount);
_totalETHAmount > winnerAmount,
"Can't withdraw over total amount"
);
(bool sent, bytes memory data) =
require(sent, "Failed to withdraw Ether to Winner");
_withdrawData = data;
_totalETHAmount = _totalETHAmount.sub(winnerAmount);
for (uint256 i = 0; i < gameLength; i ++) {
_playerETHBalance[playerList[i]] = _playerETHBalance[playerList[i]].sub(playAmount);
}
for (uint256 i = 0; i < gameLength; i++) {
emit GamePlayerStatus(
playerList[i],
playAmount,
playerScoreList[i]
);
}
emit GameWinner(playerList[winnerId], playerScoreList[winnerId]);
emit WithdrawWinner(playerList[winnerId], winnerAmount);
return true;
}
| 5,295,938
|
./full_match/1/0xcafea44b2cd8b35Ff4cd86b9E58D8D0d098b8cDC/sources/contracts/modules/staking/StakingProducts.sol
|
globalMinPriceRatio /, initialPriceRatios /, capacityReductionRatios /
|
function recalculateEffectiveWeights(uint poolId, uint[] calldata productIds) external {
IStakingPool stakingPool = getStakingPool(poolId);
(
uint globalCapacityRatio,
uint[] memory capacityReductionRatios
) = ICover(coverContract).getPriceAndCapacityRatios(productIds);
uint _totalEffectiveWeight = weights[poolId].totalEffectiveWeight;
for (uint i = 0; i < productIds.length; i++) {
uint productId = productIds[i];
StakedProduct memory _product = _products[poolId][productId];
uint16 previousEffectiveWeight = _product.lastEffectiveWeight;
_product.lastEffectiveWeight = _getEffectiveWeight(
stakingPool,
productId,
_product.targetWeight,
globalCapacityRatio,
capacityReductionRatios[i]
);
_totalEffectiveWeight = _totalEffectiveWeight - previousEffectiveWeight + _product.lastEffectiveWeight;
_products[poolId][productId] = _product;
}
weights[poolId].totalEffectiveWeight = _totalEffectiveWeight.toUint32();
}
| 4,831,765
|
// SPDX-License-Identifier: MIT
/*
██████╗ ███████╗██████╗ █████╗ ███████╗███████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝
██║ ██║█████╗ ██████╔╝███████║███████╗█████╗
██║ ██║██╔══╝ ██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝███████╗██████╔╝██║ ██║███████║███████╗
╚═════╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
* Debase: BurnPool.sol
* Description:
* Pool that issues coupons for debase sent to it. Then rewards those coupons when positive rebases happen
* Coded by: punkUnknown
*/
pragma solidity >=0.6.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./lib/SafeMathInt.sol";
import "./Curve.sol";
interface IDebasePolicy {
function upperDeviationThreshold() external view returns (uint256);
function lowerDeviationThreshold() external view returns (uint256);
function priceTargetRate() external view returns (uint256);
}
interface IOracle {
function getData() external returns (uint256, bool);
function updateData() external;
}
contract BurnPool is Ownable, Curve, Initializable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMathInt for int256;
using Address for address;
event LogStartNewDistributionCycle(
uint256 exchangeRate_,
uint256 poolShareAdded_,
uint256 rewardRate_,
uint256 periodFinish_,
bytes16 curveValue_
);
event LogNeutralRebase(bool rewardDistributionDisabled_);
event LogCouponsBought(address buyer_, uint256 amount_);
event LogSetOracle(IOracle oracle_);
event LogSetRewardBlockPeriod(uint256 rewardBlockPeriod_);
event LogSetMultiSigRewardShare(uint256 multiSigRewardShare_);
event LogSetInitialRewardShare(uint256 initialRewardShare_);
event LogSetMultiSigAddress(address multiSigAddress_);
event LogSetOracleBlockPeriod(uint256 oracleBlockPeriod_);
event LogSetEpochs(uint256 epochs_);
event LogSetCurveShifter(uint256 curveShifter_);
event LogSetMeanAndDeviationWithFormulaConstants(
bytes16 mean_,
bytes16 deviation_,
bytes16 peakScaler_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
);
event LogEmergencyWithdrawa(uint256 withdrawAmount_);
event LogRewardsAccrued(
uint256 index,
uint256 exchangeRate_,
uint256 rewardsAccrued_,
uint256 expansionPercentageScaled_,
bytes16 value_
);
event LogRewardClaimed(
address user_,
uint256 cycleIndex_,
uint256 rewardClaimed_
);
event LogNewCouponCycle(
uint256 index_,
uint256 rewardAmount_,
uint256 debasePerEpoch_,
uint256 rewardBlockPeriod_,
uint256 oracleBlockPeriod_,
uint256 oracleLastPrice_,
uint256 oracleNextUpdate_,
uint256 epochsToReward_
);
event LogOraclePriceAndPeriod(uint256 price_, uint256 period_);
uint256 internal constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
// Address of the debase policy/reward contract
IDebasePolicy public policy;
// Address of the debase token
IERC20 public debase;
// Address of the oracle contract managing opening and closing of coupon buying
IOracle public oracle;
// Address of the multiSig treasury
address public multiSigAddress;
// Address of dai staking pool with burned tokens
address public burnPool1;
// Address of debase/dai staking pool with burned tokens
address public burnPool2;
// Mean for log normal distribution
bytes16 public mean;
// Deviation for log normal distribution
bytes16 public deviation;
// Multiplied into log normal curve to raise or lower the peak. Initially set to 1 in bytes16
bytes16 public peakScaler = 0x3fff565013f27f16fc74748b3f33c2db;
// Result of 1/(Deviation*Sqrt(2*pi)) for optimized log normal calculation
bytes16 public oneDivDeviationSqrtTwoPi;
// Result of 2*(Deviation)^2 for optimized log normal calculation
bytes16 public twoDeviationSquare;
// The number rebases coupon rewards can be distributed for
uint256 public epochs;
// The total rewards in %s of the market cap distributed
uint256 public totalRewardsDistributed;
// The period after which the oracle price updates for coupon buying
uint256 public oracleBlockPeriod;
// Tracking supply expansion in relation to total supply.
// To be given out as rewards after the next contraction
uint256 public rewardsAccrued;
// Offset to shift the log normal curve
uint256 public curveShifter;
// The block duration over which rewards are given out
uint256 public rewardBlockPeriod = 6400;
// The percentage of the total supply to be given out on the first instance
// when the pool launches and the next rebase is negative
uint256 public initialRewardShare;
// The percentage of the current reward to be given in an epoch to be routed to the treasury
uint256 public multiSigRewardShare;
// The percentage of the total supply that can be claimed as rewards for the treasury
uint256 public multiSigRewardToClaimShare;
// Flag to stop rewards to be given out if rebases go from positive to neutral
bool public positiveToNeutralRebaseRewardsDisabled;
enum Rebase {POSITIVE, NEUTRAL, NEGATIVE, NONE}
// Showing last rebase that happened
Rebase public lastRebase;
// Struct saving the data related rebase cycles
struct RewardCycle {
// Shows the %s of the totalSupply to be given as reward
uint256 rewardShare;
// The debase to be rewarded as per the epoch
uint256 debasePerEpoch;
// The number of blocks to give out rewards per epoch
uint256 rewardBlockPeriod;
// The number of blocks after which the coupon oracle should update
uint256 oracleBlockPeriod;
// Last Price of the oracle used to open or close coupon buying
uint256 oracleLastPrice;
// The block number when the oracle with update next
uint256 oracleNextUpdate;
// Shows the number of epoch(rebases) to distribute rewards for
uint256 epochsToReward;
// Shows the number of epochs(rebases) rewarded
uint256 epochsRewarded;
// The number if coupouns issued/Debase sold in the contraction cycle
uint256 couponsIssued;
// The reward Rate for the distribution cycle
uint256 rewardRate;
// The period over to distribute rewards for a single epoch/cycle
uint256 periodFinish;
uint256 lastUpdateBlock;
uint256 rewardPerTokenStored;
// The rewards distributed in %s of the total supply in reward cycle
uint256 rewardDistributed;
mapping(address => uint256) userCouponBalances;
mapping(address => uint256) userRewardPerTokenPaid;
mapping(address => uint256) rewards;
}
// Array of rebase cycles
RewardCycle[] public rewardCycles;
// Lenght of the rebase cycles
uint256 public rewardCyclesLength;
modifier updateReward(address account, uint256 index) {
require(rewardCyclesLength != 0, "Cycle array is empty");
require(
index <= rewardCyclesLength.sub(1),
"Index should not me more than items in the cycle array"
);
RewardCycle storage instance = rewardCycles[index];
instance.rewardPerTokenStored = rewardPerToken(index);
instance.lastUpdateBlock = lastRewardApplicable(index);
if (account != address(0)) {
instance.rewards[account] = earned(index, account);
instance.userRewardPerTokenPaid[account] = instance
.rewardPerTokenStored;
}
_;
}
/**
* @notice Function to set the oracle period after which the price updates
* @param oracleBlockPeriod_ New oracle period
*/
function setOracleBlockPeriod(uint256 oracleBlockPeriod_)
external
onlyOwner
{
oracleBlockPeriod = oracleBlockPeriod_;
emit LogSetOracleBlockPeriod(oracleBlockPeriod);
}
/**
* @notice Function to set the offest by which to shift the log normal curve
* @param curveShifter_ New curve offset
*/
function setCurveShifter(uint256 curveShifter_) external onlyOwner {
curveShifter = curveShifter_;
emit LogSetCurveShifter(curveShifter);
}
/**
* @notice Function to set the number of epochs/rebase triggers over which to distribute rewards
* @param epochs_ New rewards epoch
*/
function setEpochs(uint256 epochs_) external onlyOwner {
epochs = epochs_;
emit LogSetEpochs(epochs);
}
/**
* @notice Function to set the oracle address for the coupon buying and closing
* @param oracle_ Address of the new oracle
*/
function setOracle(IOracle oracle_) external onlyOwner {
oracle = oracle_;
emit LogSetOracle(oracle);
}
/**
* @notice Function to set the initial reward if the pools first rebase is negative
* @param initialRewardShare_ New initial reward share in %s
*/
function setInitialRewardShare(uint256 initialRewardShare_)
external
onlyOwner
{
initialRewardShare = initialRewardShare_;
emit LogSetInitialRewardShare(initialRewardShare);
}
/**
* @notice Function to set the share of the epoch reward to be given out to treasury
* @param multiSigRewardShare_ New multiSig reward share in 5s
*/
function setMultiSigRewardShare(uint256 multiSigRewardShare_)
external
onlyOwner
{
multiSigRewardShare = multiSigRewardShare_;
emit LogSetMultiSigRewardShare(multiSigRewardShare);
}
/**
* @notice Function to set the multiSig treasury address to get treasury rewards
* @param multiSigAddress_ New multi sig treasury address
*/
function setMultiSigAddress(address multiSigAddress_) external onlyOwner {
multiSigAddress = multiSigAddress_;
emit LogSetMultiSigAddress(multiSigAddress);
}
/**
* @notice Function to set the reward duration for a single epoch reward period
* @param rewardBlockPeriod_ New block duration period
*/
function setRewardBlockPeriod(uint256 rewardBlockPeriod_)
external
onlyOwner
{
rewardBlockPeriod = rewardBlockPeriod_;
emit LogSetRewardBlockPeriod(rewardBlockPeriod);
}
/**
* @notice Function to set the mean,deviation and formula constants for log normals curve
* @param mean_ New log normal mean
* @param deviation_ New log normal deviation
* @param peakScaler_ New peak scaler value
* @param oneDivDeviationSqrtTwoPi_ New Result of 1/(Deviation*Sqrt(2*pi))
* @param twoDeviationSquare_ New Result of 2*(Deviation)^2
*/
function setMeanAndDeviationWithFormulaConstants(
bytes16 mean_,
bytes16 deviation_,
bytes16 peakScaler_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
) external onlyOwner {
mean = mean_;
deviation = deviation_;
peakScaler = peakScaler_;
oneDivDeviationSqrtTwoPi = oneDivDeviationSqrtTwoPi_;
twoDeviationSquare = twoDeviationSquare_;
emit LogSetMeanAndDeviationWithFormulaConstants(
mean,
deviation,
peakScaler,
oneDivDeviationSqrtTwoPi,
twoDeviationSquare
);
}
/**
* @notice Function that returns user coupon balance at the specified index
* @param index Cycle array index at which to get coupon balance from
*/
function getUserCouponBalance(uint256 index)
external
view
returns (uint256)
{
require(rewardCyclesLength != 0, "Cycle array is empty");
require(
index <= rewardCyclesLength.sub(1),
"Index should not me more than items in the cycle array"
);
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
return instance.userCouponBalances[msg.sender];
}
/**
* @notice Function that initializes set of variables for the pool on launch
*/
function initialize(
address debase_,
IOracle oracle_,
IDebasePolicy policy_,
address burnPool1_,
address burnPool2_,
uint256 epochs_,
uint256 oracleBlockPeriod_,
uint256 curveShifter_,
uint256 initialRewardShare_,
address multiSigAddress_,
uint256 multiSigRewardShare_,
bytes16 mean_,
bytes16 deviation_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
) external initializer onlyOwner {
debase = IERC20(debase_);
burnPool1 = burnPool1_;
burnPool2 = burnPool2_;
policy = policy_;
oracle = oracle_;
epochs = epochs_;
oracleBlockPeriod = oracleBlockPeriod_;
curveShifter = curveShifter_;
mean = mean_;
deviation = deviation_;
oneDivDeviationSqrtTwoPi = oneDivDeviationSqrtTwoPi_;
twoDeviationSquare = twoDeviationSquare_;
initialRewardShare = initialRewardShare_;
multiSigRewardShare = multiSigRewardShare_;
multiSigAddress = multiSigAddress_;
lastRebase = Rebase.NONE;
}
/**
* @notice Function that shows the current circulating balance
* @return Returns circulating balance
*/
function circBalance() public view returns (uint256) {
uint256 totalSupply = debase.totalSupply();
return
totalSupply
.sub(debase.balanceOf(address(policy)))
.sub(debase.balanceOf(burnPool1))
.sub(debase.balanceOf(burnPool2));
}
/**
* @notice Function that is called when the next rebase is negative. If the last rebase was not negative then a
* new coupon cycle starts. If the last rebase was also negative when nothing happens.
*/
function startNewCouponCycle(uint256 exchangeRate_) internal {
if (lastRebase != Rebase.NEGATIVE) {
lastRebase = Rebase.NEGATIVE;
uint256 rewardAmount;
// For the special case when the pool launches and the next rebase is negative. Meaning no rewards are accured from
// positive expansion and hence no negaitve reward cycles have started. Then we use our reward as the inital reward
// setting too bootstrap the pool.
if (rewardsAccrued == 0 && rewardCyclesLength == 0) {
// Get reward in relation to circulating balance multiplied by share
rewardAmount = circBalance().mul(initialRewardShare).div(
10**18
);
} else {
rewardAmount = circBalance()
.mul(rewardsAccrued.sub(10**18))
.div(10**18);
}
// Scale reward amount in relation debase total supply
uint256 rewardShare =
rewardAmount.mul(10**18).div(debase.totalSupply());
// Percentage amount to be claimed per epoch. Only set at the start of first reward epoch.
// Its the result of reward expansion to give out div by number of epochs to give in
uint256 debasePerEpoch = rewardShare.div(epochs);
rewardCycles.push(
RewardCycle(
rewardShare,
debasePerEpoch,
rewardBlockPeriod,
oracleBlockPeriod,
exchangeRate_,
block.number.add(oracleBlockPeriod),
epochs,
0,
0,
0,
0,
0,
0,
0
)
);
emit LogNewCouponCycle(
rewardCyclesLength,
rewardShare,
debasePerEpoch,
rewardBlockPeriod,
oracleBlockPeriod,
exchangeRate_,
block.number.add(oracleBlockPeriod),
epochs
);
rewardCyclesLength = rewardCyclesLength.add(1);
positiveToNeutralRebaseRewardsDisabled = false;
rewardsAccrued = 0;
} else {
RewardCycle storage instance =
rewardCycles[rewardCyclesLength.sub(1)];
instance.oracleLastPrice = exchangeRate_;
instance.oracleNextUpdate = block.number.add(
instance.oracleBlockPeriod
);
emit LogOraclePriceAndPeriod(
instance.oracleLastPrice,
instance.oracleNextUpdate
);
}
// Update oracle data to current timestamp
oracle.updateData();
}
/**
* @notice Function that issues rewards when a positive rebase is about to happen.
* @param exchangeRate_ The current exchange rate at rebase
* @param debasePolicyBalance The current balance of the fund contract
* @param curveValue Value of the log normal curve
* @return Returns amount of rewards to be claimed from a positive rebase
*/
function issueRewards(
uint256 exchangeRate_,
uint256 debasePolicyBalance,
bytes16 curveValue
) internal returns (uint256) {
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
instance.epochsRewarded = instance.epochsRewarded.add(1);
// Scale reward percentage in relation curve value
uint256 debaseShareToBeRewarded =
bytes16ToUnit256(curveValue, instance.debasePerEpoch);
// Claim multi sig reward in relation to scaled debase reward
multiSigRewardToClaimShare = debaseShareToBeRewarded
.mul(multiSigRewardShare)
.div(10**18);
// Convert reward to token amount
uint256 debaseClaimAmount =
debase.totalSupply().mul(debaseShareToBeRewarded).div(10**18);
// Convert multisig reward to token amount
uint256 multiSigRewardToClaimAmount =
debase.totalSupply().mul(multiSigRewardToClaimShare).div(10**18);
uint256 totalDebaseToClaim =
debaseClaimAmount.add(multiSigRewardToClaimAmount);
if (totalDebaseToClaim <= debasePolicyBalance) {
// Start new reward distribution cycle in relation to just debase claim amount
startNewDistributionCycle(
exchangeRate_,
totalDebaseToClaim,
debaseShareToBeRewarded,
curveValue
);
return totalDebaseToClaim;
}
return 0;
}
/**
* @notice Function called by treasury to claim multi sig reward percentage. Since claims can only happen after the rebase reward
* contract has rewarded the pool
*/
function claimMultiSigReward() external {
require(
msg.sender == multiSigAddress,
"Only multiSigAddress can claim reward"
);
uint256 amountToClaim =
debase.totalSupply().mul(multiSigRewardToClaimShare).div(10**18);
debase.transfer(multiSigAddress, amountToClaim);
multiSigRewardToClaimShare = 0;
}
/**
* @notice Function called by the reward contract to start new distribution cycles
* @param supplyDelta_ Supply delta of the rebase to happen
* @param rebaseLag_ Rebase lag applied to the supply delta
* @param exchangeRate_ Exchange rate at which the rebase is happening
* @param debasePolicyBalance Current balance of the policy contract
* @return Amount of debase to be claimed from the reward contract
*/
function checkStabilizerAndGetReward(
int256 supplyDelta_,
int256 rebaseLag_,
uint256 exchangeRate_,
uint256 debasePolicyBalance
) external returns (uint256) {
require(
msg.sender == address(policy),
"Only debase policy contract can call this"
);
if (supplyDelta_ < 0) {
startNewCouponCycle(exchangeRate_);
} else if (supplyDelta_ == 0) {
if (lastRebase == Rebase.POSITIVE) {
positiveToNeutralRebaseRewardsDisabled = true;
}
lastRebase = Rebase.NEUTRAL;
emit LogNeutralRebase(positiveToNeutralRebaseRewardsDisabled);
} else {
lastRebase = Rebase.POSITIVE;
uint256 currentSupply = debase.totalSupply();
uint256 newSupply = uint256(supplyDelta_.abs()).add(currentSupply);
if (newSupply > MAX_SUPPLY) {
newSupply = MAX_SUPPLY;
}
// Get the percentage expansion that will happen from the rebase
uint256 expansionPercentage =
newSupply.mul(10**18).div(currentSupply).sub(10**18);
uint256 targetRate =
policy.priceTargetRate().add(policy.upperDeviationThreshold());
// Get the difference between the current price and the target price (1.05$ Dai)
uint256 offset = exchangeRate_.add(curveShifter).sub(targetRate);
// Use the offset to get the current curve value
bytes16 value =
getCurveValue(
offset,
mean,
oneDivDeviationSqrtTwoPi,
twoDeviationSquare
);
// Expansion percentage is scaled in relation to the value
uint256 expansionPercentageScaled =
bytes16ToUnit256(value, expansionPercentage).add(10**18);
// On our first positive rebase rewardsAccrued rebase will be the expansion percentage
if (rewardsAccrued == 0) {
rewardsAccrued = expansionPercentageScaled;
} else {
// Subsequest positive rebases will be compounded with previous rebases
rewardsAccrued = rewardsAccrued
.mul(expansionPercentageScaled)
.div(10**18);
}
emit LogRewardsAccrued(
rewardCyclesLength,
exchangeRate_,
rewardsAccrued,
expansionPercentageScaled,
value
);
// Rewards will not be issued if
// 1. We go from neutral to positive and back to neutral rebase
// 2. If now reward cycle has happened
// 3. If no coupons bought in the expansion cycle
// 4. If not all epochs have been rewarded
if (
!positiveToNeutralRebaseRewardsDisabled &&
rewardCyclesLength != 0 &&
rewardCycles[rewardCyclesLength.sub(1)].couponsIssued != 0 &&
rewardCycles[rewardCyclesLength.sub(1)].epochsRewarded < epochs
) {
return issueRewards(exchangeRate_, debasePolicyBalance, value);
}
}
return 0;
}
/**
* @notice Function that checks the currect price of the coupon oracle. If oracle price period has finished
* then another oracle update is called.
*/
function checkPriceOrUpdate() internal {
uint256 lowerPriceThreshold =
policy.priceTargetRate().sub(policy.lowerDeviationThreshold());
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
if (block.number > instance.oracleNextUpdate) {
bool valid;
(instance.oracleLastPrice, valid) = oracle.getData();
require(valid, "Price is invalid");
instance.oracleNextUpdate = block.number.add(
instance.oracleBlockPeriod
);
emit LogOraclePriceAndPeriod(
instance.oracleLastPrice,
instance.oracleNextUpdate
);
}
require(
instance.oracleLastPrice < lowerPriceThreshold,
"Can only buy coupons if price is lower than lower threshold"
);
}
/**
* @notice Function that allows users to buy coupuns by send in debase to the contract. When ever coupons are being bought
* the current we check the TWAP price of the debase pair. If the price is above the lower threshold price (0.95 dai)
* then no coupons can be bought. If the price is below than coupons can be bought. The debase sent are routed to the
* reward contract.
* @param debaseSent Debase amount sent
*/
function buyCoupons(uint256 debaseSent) external {
require(
!address(msg.sender).isContract(),
"Caller must not be a contract"
);
require(
lastRebase == Rebase.NEGATIVE,
"Can only buy coupons with last rebase was negative"
);
checkPriceOrUpdate();
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
instance.userCouponBalances[msg.sender] = instance.userCouponBalances[
msg.sender
]
.add(debaseSent);
instance.couponsIssued = instance.couponsIssued.add(debaseSent);
emit LogCouponsBought(msg.sender, debaseSent);
debase.safeTransferFrom(msg.sender, address(policy), debaseSent);
}
function emergencyWithdraw() external onlyOwner {
uint256 withdrawAmount = debase.balanceOf(address(this));
debase.safeTransfer(address(policy), withdrawAmount);
emit LogEmergencyWithdrawa(withdrawAmount);
}
function lastRewardApplicable(uint256 index)
internal
view
returns (uint256)
{
return Math.min(block.number, rewardCycles[index].periodFinish);
}
function rewardPerToken(uint256 index) internal view returns (uint256) {
RewardCycle memory instance = rewardCycles[index];
if (instance.couponsIssued == 0) {
return instance.rewardPerTokenStored;
}
return
instance.rewardPerTokenStored.add(
lastRewardApplicable(index)
.sub(instance.lastUpdateBlock)
.mul(instance.rewardRate)
.mul(10**18)
.div(instance.couponsIssued)
);
}
function earned(uint256 index, address account)
public
view
returns (uint256)
{
require(rewardCyclesLength != 0, "Cycle array is empty");
require(
index <= rewardCyclesLength.sub(1),
"Index should not me more than items in the cycle array"
);
RewardCycle storage instance = rewardCycles[index];
return
instance.userCouponBalances[account]
.mul(
rewardPerToken(index).sub(
instance.userRewardPerTokenPaid[account]
)
)
.div(10**18)
.add(instance.rewards[account]);
}
function getReward(uint256 index) public updateReward(msg.sender, index) {
uint256 reward = earned(index, msg.sender);
if (reward > 0) {
RewardCycle storage instance = rewardCycles[index];
instance.rewards[msg.sender] = 0;
uint256 rewardToClaim =
debase.totalSupply().mul(reward).div(10**18);
instance.rewardDistributed = instance.rewardDistributed.add(reward);
totalRewardsDistributed = totalRewardsDistributed.add(reward);
emit LogRewardClaimed(msg.sender, index, rewardToClaim);
debase.safeTransfer(msg.sender, rewardToClaim);
}
}
function startNewDistributionCycle(
uint256 exchangeRate_,
uint256 totalDebaseToClaim,
uint256 poolTotalShare,
bytes16 curveValue
) internal updateReward(address(0), rewardCyclesLength.sub(1)) {
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
// https://sips.synthetix.io/sips/sip-77
uint256 poolBal =
totalDebaseToClaim.add(debase.balanceOf(address(this)));
require(
poolBal < uint256(-1) / 10**18,
"Rewards: rewards too large, would lock"
);
if (block.number >= instance.periodFinish) {
instance.rewardRate = poolTotalShare.div(
instance.rewardBlockPeriod
);
} else {
uint256 remaining = instance.periodFinish.sub(block.number);
uint256 leftover = remaining.mul(instance.rewardRate);
instance.rewardRate = poolTotalShare.add(leftover).div(
instance.rewardBlockPeriod
);
}
instance.lastUpdateBlock = block.number;
instance.periodFinish = block.number.add(instance.rewardBlockPeriod);
emit LogStartNewDistributionCycle(
exchangeRate_,
poolTotalShare,
instance.rewardRate,
instance.periodFinish,
curveValue
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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 arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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.
*/
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;
}
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// 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);
}
}
}
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.6.6;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
// SPDX-License-Identifier: MIT
/*
██████╗ ███████╗██████╗ █████╗ ███████╗███████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝
██║ ██║█████╗ ██████╔╝███████║███████╗█████╗
██║ ██║██╔══╝ ██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝███████╗██████╔╝██║ ██║███████║███████╗
╚═════╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
* Debase: Curve.sol
* Description:
* Log normal curve to generate curve values in relation to curve input
* Coded by: punkUnknown
*/
pragma solidity >=0.6.6;
import "./lib/ABDKMathQuad.sol";
contract Curve {
bytes16 private MINUS_ONE = 0xbfff0000000000000000000000000000;
bytes16 private TENE18 = 0x403abc16d674ec800000000000000000;
bytes16 private ONE = 0x3fff0000000000000000000000000000;
/**
* @notice Function to calculate log normal values using the formula
* (1/offset * deviation * sqrt(2 * pi))* exp( -((ln offset - deviation)^2)/(2 * deviation^2) )
* @param priceDelta_ Used as offset for log normal curve
* @param mean_ Mean for log normal curve
* @param oneDivDeviationSqrtTwoPi_ Calculation of 1/(deviation * sqrt(2*pi))
* @param twoDeviationSquare_ Calculation of 2 * deviation^2
*/
function getCurveValue(
uint256 priceDelta_,
bytes16 mean_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
) public view returns (bytes16) {
bytes16 priceDelta =
ABDKMathQuad.div(ABDKMathQuad.fromUInt(priceDelta_), TENE18);
bytes16 res1 = ABDKMathQuad.sub(ABDKMathQuad.ln(priceDelta), mean_);
bytes16 res2 =
ABDKMathQuad.mul(
MINUS_ONE,
ABDKMathQuad.div(
ABDKMathQuad.mul(res1, res1),
twoDeviationSquare_
)
);
return
ABDKMathQuad.mul(
ABDKMathQuad.mul(
ABDKMathQuad.div(ONE, priceDelta),
oneDivDeviationSqrtTwoPi_
),
ABDKMathQuad.exp(res2)
);
}
function uint256ToBytes16(uint256 number_, uint256 scale_)
public
pure
returns (bytes16)
{
bytes16 number = ABDKMathQuad.fromUInt(number_);
bytes16 scale = ABDKMathQuad.fromUInt(scale_);
return ABDKMathQuad.div(number, scale);
}
function bytes16ToUnit256(bytes16 number_, uint256 scale_)
public
pure
returns (uint256)
{
bytes16 scale = ABDKMathQuad.fromUInt(scale_);
return ABDKMathQuad.toUInt(ABDKMathQuad.mul(number_, scale));
}
}
// 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: BSD-4-Clause
/*
* ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity >=0.6.6;
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant POSITIVE_ZERO = 0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt (int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
// We rely on overflow behavior here
uint256 result = uint256 (x > 0 ? x : -x);
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16383 + msb << 112;
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt (bytes16 x) internal pure returns (int256) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (result);
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt (uint256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
uint256 result = x;
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16383 + msb << 112;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt (bytes16 x) internal pure returns (uint256) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require (uint128 (x) < 0x80000000000000000000000000000000); // Negative
require (exponent <= 16638); // Overflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128 (int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
// We rely on overflow behavior here
uint256 result = uint256 (x > 0 ? x : -x);
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16255 + msb << 112;
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128 (bytes16 x) internal pure returns (int256) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (result);
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64 (int128 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
// We rely on overflow behavior here
uint256 result = uint128 (x > 0 ? x : -x);
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16319 + msb << 112;
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64 (bytes16 x) internal pure returns (int128) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x80000000000000000000000000000000);
return -int128 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (result);
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple (bytes32 x) internal pure returns (bytes16) {
bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0;
uint256 exponent = uint256 (x) >> 236 & 0x7FFFF;
uint256 significand = uint256 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
}
if (exponent > 278526)
return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else if (exponent < 245649)
return negative ? NEGATIVE_ZERO : POSITIVE_ZERO;
else if (exponent < 245761) {
significand = (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> 245885 - exponent;
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128 (significand | exponent << 112);
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16 (result);
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple (bytes16 x) internal pure returns (bytes32) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
uint256 result = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb (result);
result = result << 236 - msb & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128 (x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32 (result);
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble (bytes8 x) internal pure returns (bytes16) {
uint256 exponent = uint64 (x) >> 52 & 0x7FF;
uint256 result = uint64 (x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF) exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb (result);
result = result << 112 - msb & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0)
result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble (bytes16 x) internal pure returns (bytes8) {
bool negative = uint128 (x) >= 0x80000000000000000000000000000000;
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
uint256 significand = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000; // NaN
else return negative ?
bytes8 (0xFFF0000000000000) : // -Infinity
bytes8 (0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return negative ?
bytes8 (0xFFF0000000000000) : // -Infinity
bytes8 (0x7FF0000000000000); // Infinity
else if (exponent < 15309)
return negative ?
bytes8 (0x8000000000000000) : // -0
bytes8 (0x0000000000000000); // 0
else if (exponent < 15361) {
significand = (significand | 0x10000000000000000000000000000) >> 15421 - exponent;
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64 (significand | exponent << 52);
if (negative) result |= 0x8000000000000000;
return bytes8 (result);
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN (bytes16 x) internal pure returns (bool) {
return uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF >
0x7FFF0000000000000000000000000000;
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity (bytes16 x) internal pure returns (bool) {
return uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ==
0x7FFF0000000000000000000000000000;
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign (bytes16 x) internal pure returns (int8) {
uint128 absoluteX = uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128 (x) >= 0x80000000000000000000000000000000) return -1;
else return 1;
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp (bytes16 x, bytes16 y) internal pure returns (int8) {
uint128 absoluteX = uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128 (y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require (x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX = uint128 (x) >= 0x80000000000000000000000000000000;
bool negativeY = uint128 (y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8 (1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8 (1) : -1;
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq (bytes16 x, bytes16 y) internal pure returns (bool) {
if (x == y) {
return uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF <
0x7FFF0000000000000000000000000000;
} else return false;
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add (bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 yExponent = uint128 (y) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128 (x) >= 0x80000000000000000000000000000000;
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128 (y) >= 0x80000000000000000000000000000000;
uint256 ySignifier = uint128 (y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return y == NEGATIVE_ZERO ? POSITIVE_ZERO : y;
else if (ySignifier == 0) return x == NEGATIVE_ZERO ? POSITIVE_ZERO : x;
else {
int256 delta = int256 (xExponent) - int256 (yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256 (delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256 (-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF)
return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000) xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return bytes16 (uint128 (
(xSign ? 0x80000000000000000000000000000000 : 0) |
(xExponent << 112) |
xSignifier));
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1) ySignifier = (ySignifier - 1 >> uint256 (delta - 1)) + 1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1) xSignifier = (xSignifier - 1 >> uint256 (-delta - 1)) + 1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0)
return POSITIVE_ZERO;
uint256 msb = msb (xSignifier);
if (msb == 113) {
xSignifier = xSignifier >> 1 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier = xSignifier << shift & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF)
return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else return bytes16 (uint128 (
(xSign ? 0x80000000000000000000000000000000 : 0) |
(xExponent << 112) |
xSignifier));
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub (bytes16 x, bytes16 y) internal pure returns (bytes16) {
return add (x, y ^ 0x80000000000000000000000000000000);
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul (bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 yExponent = uint128 (y) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x ^ y & 0x80000000000000000000000000000000;
else if (x ^ y == 0x80000000000000000000000000000000) return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ y & 0x80000000000000000000000000000000;
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ x & 0x80000000000000000000000000000000;
} else {
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier = uint128 (y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ?
NEGATIVE_ZERO : POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb =
xSignifier >= 0x200000000000000000000000000000000000000000000000000000000 ? 225 :
xSignifier >= 0x100000000000000000000000000000000000000000000000000000000 ? 224 :
msb (xSignifier);
if (xExponent + msb < 16496) { // Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) { // Subnormal
if (xExponent < 16496)
xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496)
xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112)
xSignifier >>= msb - 112;
else if (msb < 112)
xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return bytes16 (uint128 (uint128 ((x ^ y) & 0x80000000000000000000000000000000) |
xExponent << 112 | xSignifier));
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div (bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 yExponent = uint128 (y) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ y & 0x80000000000000000000000000000000;
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else return POSITIVE_ZERO | (x ^ y) & 0x80000000000000000000000000000000;
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return POSITIVE_INFINITY | (x ^ y) & 0x80000000000000000000000000000000;
} else {
uint256 ySignifier = uint128 (y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint shift = 226 - msb (xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
}
else {
xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ?
NEGATIVE_ZERO : POSITIVE_ZERO;
assert (xSignifier >= 0x1000000000000000000000000000);
uint256 msb =
xSignifier >= 0x80000000000000000000000000000 ? msb (xSignifier) :
xSignifier >= 0x40000000000000000000000000000 ? 114 :
xSignifier >= 0x20000000000000000000000000000 ? 113 : 112;
if (xExponent + msb > yExponent + 16497) { // Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) { // Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) { // Subnormal
if (xExponent + 16380 > yExponent)
xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent)
xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else { // Normal
if (msb > 112)
xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return bytes16 (uint128 (uint128 ((x ^ y) & 0x80000000000000000000000000000000) |
xExponent << 112 | xSignifier));
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg (bytes16 x) internal pure returns (bytes16) {
return x ^ 0x80000000000000000000000000000000;
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs (bytes16 x) internal pure returns (bytes16) {
return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt (bytes16 x) internal pure returns (bytes16) {
if (uint128 (x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = xExponent + 16383 >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 113;
else {
uint256 msb = msb (xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= shift - 112 >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 112;
else {
uint256 msb = msb (xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= shift - 112 >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return bytes16 (uint128 (xExponent << 112 | r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2 (bytes16 x) internal pure returns (bytes16) {
if (uint128 (x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000) return POSITIVE_ZERO;
else {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = msb (xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift = 112 - msb (resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (resultSignifier < 0x10000000000000000000000000000) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return bytes16 (uint128 ((resultNegative ? 0x80000000000000000000000000000000 : 0) |
resultExponent << 112 | resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln (bytes16 x) internal pure returns (bytes16) {
return mul (log_2 (x), 0x3FFE62E42FEFA39EF35793C7673007E5);
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2 (bytes16 x) internal pure returns (bytes16) {
bool xNegative = uint128 (x) > 0x80000000000000000000000000000000;
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397)
return xNegative ? POSITIVE_ZERO : POSITIVE_INFINITY;
else if (xExponent < 16255)
return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367)
xSignifier <<= xExponent - 16367;
else if (xExponent < 16367)
xSignifier >>= 16367 - xExponent;
if (xNegative && xSignifier > 0x406E00000000000000000000000000000000)
return POSITIVE_ZERO;
if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
return POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (xSignifier & 0x40000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (xSignifier & 0x20000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (xSignifier & 0x10000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (xSignifier & 0x8000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (xSignifier & 0x4000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (xSignifier & 0x2000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (xSignifier & 0x1000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (xSignifier & 0x800000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (xSignifier & 0x400000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (xSignifier & 0x200000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (xSignifier & 0x100000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (xSignifier & 0x80000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (xSignifier & 0x40000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (xSignifier & 0x20000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000162E525EE054754457D5995292026 >> 128;
if (xSignifier & 0x10000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (xSignifier & 0x8000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (xSignifier & 0x4000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (xSignifier & 0x2000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (xSignifier & 0x1000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (xSignifier & 0x800000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (xSignifier & 0x400000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (xSignifier & 0x200000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (xSignifier & 0x100000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (xSignifier & 0x80000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (xSignifier & 0x40000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (xSignifier & 0x20000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (xSignifier & 0x10000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (xSignifier & 0x8000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (xSignifier & 0x4000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (xSignifier & 0x2000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (xSignifier & 0x1000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (xSignifier & 0x800000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (xSignifier & 0x400000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (xSignifier & 0x200000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (xSignifier & 0x100000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (xSignifier & 0x80000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (xSignifier & 0x40000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (xSignifier & 0x20000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (xSignifier & 0x10000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (xSignifier & 0x8000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (xSignifier & 0x4000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (xSignifier & 0x2000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (xSignifier & 0x1000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (xSignifier & 0x800000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (xSignifier & 0x400000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (xSignifier & 0x200000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (xSignifier & 0x100000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (xSignifier & 0x80000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (xSignifier & 0x40000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (xSignifier & 0x20000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (xSignifier & 0x10000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (xSignifier & 0x8000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (xSignifier & 0x4000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (xSignifier & 0x2000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (xSignifier & 0x1000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (xSignifier & 0x800000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (xSignifier & 0x400000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (xSignifier & 0x200000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000162E42FEFA39EF366F >> 128;
if (xSignifier & 0x100000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (xSignifier & 0x80000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (xSignifier & 0x40000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (xSignifier & 0x20000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (xSignifier & 0x10000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000B17217F7D1CF79AB >> 128;
if (xSignifier & 0x8000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5 >> 128;
if (xSignifier & 0x4000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000002C5C85FDF473DE6A >> 128;
if (xSignifier & 0x2000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000162E42FEFA39EF34 >> 128;
if (xSignifier & 0x1000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000B17217F7D1CF799 >> 128;
if (xSignifier & 0x800000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000058B90BFBE8E7BCC >> 128;
if (xSignifier & 0x400000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000002C5C85FDF473DE5 >> 128;
if (xSignifier & 0x200000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000162E42FEFA39EF2 >> 128;
if (xSignifier & 0x100000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000B17217F7D1CF78 >> 128;
if (xSignifier & 0x80000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000058B90BFBE8E7BB >> 128;
if (xSignifier & 0x40000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000002C5C85FDF473DD >> 128;
if (xSignifier & 0x20000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000162E42FEFA39EE >> 128;
if (xSignifier & 0x10000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000B17217F7D1CF6 >> 128;
if (xSignifier & 0x8000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000058B90BFBE8E7A >> 128;
if (xSignifier & 0x4000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000002C5C85FDF473C >> 128;
if (xSignifier & 0x2000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000162E42FEFA39D >> 128;
if (xSignifier & 0x1000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000B17217F7D1CE >> 128;
if (xSignifier & 0x800000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000058B90BFBE8E6 >> 128;
if (xSignifier & 0x400000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000002C5C85FDF472 >> 128;
if (xSignifier & 0x200000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000162E42FEFA38 >> 128;
if (xSignifier & 0x100000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000B17217F7D1B >> 128;
if (xSignifier & 0x80000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000058B90BFBE8D >> 128;
if (xSignifier & 0x40000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000002C5C85FDF46 >> 128;
if (xSignifier & 0x20000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000162E42FEFA2 >> 128;
if (xSignifier & 0x10000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000B17217F7D0 >> 128;
if (xSignifier & 0x8000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000058B90BFBE7 >> 128;
if (xSignifier & 0x4000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000002C5C85FDF3 >> 128;
if (xSignifier & 0x2000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000162E42FEF9 >> 128;
if (xSignifier & 0x1000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000B17217F7C >> 128;
if (xSignifier & 0x800000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000058B90BFBD >> 128;
if (xSignifier & 0x400000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000002C5C85FDE >> 128;
if (xSignifier & 0x200000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000162E42FEE >> 128;
if (xSignifier & 0x100000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000B17217F6 >> 128;
if (xSignifier & 0x80000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000058B90BFA >> 128;
if (xSignifier & 0x40000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000002C5C85FC >> 128;
if (xSignifier & 0x20000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000162E42FD >> 128;
if (xSignifier & 0x10000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000B17217E >> 128;
if (xSignifier & 0x8000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000058B90BE >> 128;
if (xSignifier & 0x4000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000002C5C85E >> 128;
if (xSignifier & 0x2000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000162E42E >> 128;
if (xSignifier & 0x1000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000B17216 >> 128;
if (xSignifier & 0x800000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000058B90A >> 128;
if (xSignifier & 0x400000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000002C5C84 >> 128;
if (xSignifier & 0x200000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000162E41 >> 128;
if (xSignifier & 0x100000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000B1720 >> 128;
if (xSignifier & 0x80000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000058B8F >> 128;
if (xSignifier & 0x40000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000002C5C7 >> 128;
if (xSignifier & 0x20000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000162E3 >> 128;
if (xSignifier & 0x10000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000B171 >> 128;
if (xSignifier & 0x8000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000058B8 >> 128;
if (xSignifier & 0x4000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000002C5B >> 128;
if (xSignifier & 0x2000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000162D >> 128;
if (xSignifier & 0x1000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000B16 >> 128;
if (xSignifier & 0x800 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000058A >> 128;
if (xSignifier & 0x400 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000002C4 >> 128;
if (xSignifier & 0x200 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000161 >> 128;
if (xSignifier & 0x100 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000000B0 >> 128;
if (xSignifier & 0x80 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000057 >> 128;
if (xSignifier & 0x40 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000002B >> 128;
if (xSignifier & 0x20 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000015 >> 128;
if (xSignifier & 0x10 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000000A >> 128;
if (xSignifier & 0x8 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000004 >> 128;
if (xSignifier & 0x4 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000001 >> 128;
if (!xNegative) {
resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier = resultSignifier >> resultExponent - 16367;
resultExponent = 0;
}
return bytes16 (uint128 (resultExponent << 112 | resultSignifier));
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp (bytes16 x) internal pure returns (bytes16) {
return pow_2 (mul (x, 0x3FFF71547652B82FE1777D0FFDA0D23A));
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function msb (uint256 x) private pure returns (uint256) {
require (x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) { x >>= 128; result += 128; }
if (x >= 0x10000000000000000) { x >>= 64; result += 64; }
if (x >= 0x100000000) { x >>= 32; result += 32; }
if (x >= 0x10000) { x >>= 16; result += 16; }
if (x >= 0x100) { x >>= 8; result += 8; }
if (x >= 0x10) { x >>= 4; result += 4; }
if (x >= 0x4) { x >>= 2; result += 2; }
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
|
Function to set the share of the epoch reward to be given out to treasury multiSigRewardShare_ New multiSig reward share in 5s/
|
function setMultiSigRewardShare(uint256 multiSigRewardShare_)
external
onlyOwner
{
multiSigRewardShare = multiSigRewardShare_;
emit LogSetMultiSigRewardShare(multiSigRewardShare);
}
| 1,329,943
|
pragma solidity ^0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
**/
library SafeMathLib{
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
**/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @dev Abstract contract for approveAndCall.
**/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
/**
* @title Game Tester Token
* @dev ERC20 contract utilizing ERC865-ish structure (based on the CoinvestTokenV2 contract)
* @dev to allow users to pay Ethereum fees in tokens.
**/
contract GameTesterToken is Ownable {
using SafeMathLib for uint256;
string public constant symbol = "GTCOIN";
string public constant name = "Game Tester";
uint8 public constant decimals = 18;
uint256 private _totalSupply = 100000000 * (10 ** 18);
// Function sigs to be used within contract for signature recovery.
bytes4 internal constant transferSig = 0xa9059cbb;
bytes4 internal constant approveSig = 0x095ea7b3;
bytes4 internal constant increaseApprovalSig = 0xd73dd623;
bytes4 internal constant decreaseApprovalSig = 0x66188463;
bytes4 internal constant approveAndCallSig = 0xcae9ca51;
bytes4 internal constant revokeSignatureSig = 0xe40d89e5;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// Keeps track of the last nonce sent from user. Used for delegated functions.
mapping (address => uint256) nonces;
// Mapping of past used hashes: true if already used.
mapping (address => mapping (bytes => bool)) invalidSignatures;
// Mapping of finalized ERC865 standard sigs => our function sigs for future-proofing
mapping (bytes4 => bytes4) public standardSigs;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed from, address indexed spender, uint tokens);
event SignatureRedeemed(bytes _sig, address indexed from);
/**
* @dev Set owner and beginning balance.
**/
constructor()
public
{
balances[msg.sender] = _totalSupply;
}
/**
* @dev This code allows us to redirect pre-signed calls with different function selectors to our own.
**/
function ()
public
{
bytes memory calldata = msg.data;
bytes4 new_selector = standardSigs[msg.sig];
require(new_selector != 0);
assembly {
mstore(add(0x20, calldata), new_selector)
}
require(address(this).delegatecall(calldata));
assembly {
if iszero(eq(returndatasize, 0x20)) { revert(0, 0) }
returndatacopy(0, 0, returndatasize)
return(0, returndatasize)
}
}
/** ******************************** ERC20 ********************************* **/
/**
* @dev Transfers coins from one address to another.
* @param _to The recipient of the transfer amount.
* @param _amount The amount of tokens to transfer.
**/
function transfer(address _to, uint256 _amount)
public
returns (bool success)
{
require(_transfer(msg.sender, _to, _amount));
return true;
}
/**
* @dev An allowed address can transfer tokens from another's address.
* @param _from The owner of the tokens to be transferred.
* @param _to The address to which the tokens will be transferred.
* @param _amount The amount of tokens to be transferred.
**/
function transferFrom(address _from, address _to, uint _amount)
public
returns (bool success)
{
require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
require(_transfer(_from, _to, _amount));
return true;
}
/**
* @dev Approves a wallet to transfer tokens on one's behalf.
* @param _spender The wallet approved to spend tokens.
* @param _amount The amount of tokens approved to spend.
**/
function approve(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_approve(msg.sender, _spender, _amount));
return true;
}
/**
* @dev Increases the allowed amount for spender from msg.sender.
* @param _spender The address to increase allowed amount for.
* @param _amount The amount of tokens to increase allowed amount by.
**/
function increaseApproval(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_increaseApproval(msg.sender, _spender, _amount));
return true;
}
/**
* @dev Decreases the allowed amount for spender from msg.sender.
* @param _spender The address to decrease allowed amount for.
* @param _amount The amount of tokens to decrease allowed amount by.
**/
function decreaseApproval(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_decreaseApproval(msg.sender, _spender, _amount));
return true;
}
/**
* @dev Used to approve an address and call a function on it in the same transaction.
* @dev _spender The address to be approved to spend GTCOIN.
* @dev _amount The amount of GTCOIN to be approved to spend.
* @dev _data The data to send to the called contract.
**/
function approveAndCall(address _spender, uint256 _amount, bytes _data)
public
returns (bool success)
{
require(_approve(msg.sender, _spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(msg.sender, _amount, address(this), _data);
return true;
}
/** ****************************** Internal ******************************** **/
/**
* @dev Internal transfer for all functions that transfer.
* @param _from The address that is transferring coins.
* @param _to The receiving address of the coins.
* @param _amount The amount of coins being transferred.
**/
function _transfer(address _from, address _to, uint256 _amount)
internal
returns (bool success)
{
require (_to != address(0));
require(balances[_from] >= _amount);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Internal approve for all functions that require an approve.
* @param _owner The owner who is allowing spender to use their balance.
* @param _spender The wallet approved to spend tokens.
* @param _amount The amount of tokens approved to spend.
**/
function _approve(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
allowed[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
return true;
}
/**
* @dev Increases the allowed by "_amount" for "_spender" from "owner"
* @param _owner The address that tokens may be transferred from.
* @param _spender The address that may transfer these tokens.
* @param _amount The amount of tokens to transfer.
**/
function _increaseApproval(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
allowed[_owner][_spender] = allowed[_owner][_spender].add(_amount);
emit Approval(_owner, _spender, allowed[_owner][_spender]);
return true;
}
/**
* @dev Decreases the allowed by "_amount" for "_spender" from "_owner"
* @param _owner The owner of the tokens to decrease allowed for.
* @param _spender The spender whose allowed will decrease.
* @param _amount The amount of tokens to decrease allowed by.
**/
function _decreaseApproval(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
if (allowed[_owner][_spender] <= _amount) allowed[_owner][_spender] = 0;
else allowed[_owner][_spender] = allowed[_owner][_spender].sub(_amount);
emit Approval(_owner, _spender, allowed[_owner][_spender]);
return true;
}
/** ************************ Delegated Functions *************************** **/
/**
* @dev Called by delegate with a signed hash of the transaction data to allow a user
* @dev to transfer tokens without paying gas in Ether (they pay in GTCOIN instead).
* @param _signature Signed hash of data for this transfer.
* @param _to The address to transfer GTCOIN to.
* @param _value The amount of GTCOIN to transfer.
* @param _gasPrice Price (IN GTCOIN) that will be paid per unit of gas by user to "delegate".
* @param _nonce Nonce of the user's new transaction (to make signatures unique, not to be confused with address transaction nonce).
**/
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
// Log starting gas left of transaction for later gas price calculations.
uint256 gas = gasleft();
// Recover signer address from signature; ensure address is valid.
address from = recoverPreSigned(_signature, transferSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
// Require the hash has not been used, declare it used, increment nonce.
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
// Internal transfer.
require(_transfer(from, _to, _value));
// If the delegate is charging, pay them for gas in GTCOIN.
if (_gasPrice > 0) {
// 35000 because of base fee of 21000 and ~14000 for the fee transfer.
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Called by a delegate with signed hash to approve a transaction for user.
* @dev All variables equivalent to transfer except _to:
* @param _to The address that will be approved to transfer GTCOIN from user's wallet.
**/
function approvePreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, approveSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_approve(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Used to increase the amount allowed for "_to" to spend from "from"
* @dev A bare approve allows potentially nasty race conditions when using a delegate.
**/
function increaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, increaseApprovalSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_increaseApproval(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Added for the same reason as increaseApproval. Decreases to 0 if "_value" is greater than allowed.
**/
function decreaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, decreaseApprovalSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_decreaseApproval(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev approveAndCallPreSigned allows a user to approve a contract and call a function on it
* @dev in the same transaction. As with the other presigneds, a delegate calls this with signed data from user.
* @dev This function is the big reason we're using gas price and calculating gas use.
* @dev Using this with the contract can result in varying gas costs.
* @param _extraData The data to send to the contract.
**/
function approveAndCallPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(356)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, approveAndCallSig, _to, _value, _extraData, _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_approve(from, _to, _value));
ApproveAndCallFallBack(_to).receiveApproval(from, _value, address(this), _extraData);
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/** *************************** Revoke PreSigned ************************** **/
/**
* @dev Revoke signature without going through a delegate.
* @param _sigToRevoke The signature that you no longer want to be used.
**/
function revokeSignature(bytes _sigToRevoke)
public
returns (bool)
{
invalidSignatures[msg.sender][_sigToRevoke] = true;
emit SignatureRedeemed(_sigToRevoke, msg.sender);
return true;
}
/**
* @dev Revoke signature through a delegate.
* @param _signature The signature allowing this revocation.
* @param _sigToRevoke The signature that you would like revoked.
* @param _gasPrice The amount of token wei to be paid for each uint of gas.
**/
function revokeSignaturePreSigned(
bytes _signature,
bytes _sigToRevoke,
uint256 _gasPrice)
public
validPayload(356)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverRevokeHash(_signature, _sigToRevoke, _gasPrice);
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
invalidSignatures[from][_sigToRevoke] = true;
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Get hash for a revocation.
* @param _sigToRevoke The signature to be revoked.
* @param _gasPrice The amount to be paid to delegate for sending this tx.
**/
function getRevokeHash(bytes _sigToRevoke, uint256 _gasPrice)
public
pure
returns (bytes32 txHash)
{
return keccak256(revokeSignatureSig, _sigToRevoke, _gasPrice);
}
/**
* @dev Recover the address from a revocation signature.
* @param _sigToRevoke The signature to be revoked.
* @param _signature The signature allowing this revocation.
* @param _gasPrice The amount of token wei to be paid for each unit of gas.
**/
function recoverRevokeHash(bytes _signature, bytes _sigToRevoke, uint256 _gasPrice)
public
pure
returns (address from)
{
return ecrecoverFromSig(getSignHash(getRevokeHash(_sigToRevoke, _gasPrice)), _signature);
}
/** ************************** PreSigned Constants ************************ **/
/**
* @dev Used in frontend and contract to get hashed data of any given pre-signed transaction.
* @param _to The address to transfer GTCOIN to.
* @param _value The amount of GTCOIN to be transferred.
* @param _extraData Extra data of tx if needed. Transfers and approves will leave this null.
* @param _function Function signature of the pre-signed function being used.
* @param _gasPrice The agreed-upon amount of GTCOIN to be paid per unit of gas.
* @param _nonce The user's nonce of the new transaction.
**/
function getPreSignedHash(
bytes4 _function,
address _to,
uint256 _value,
bytes _extraData,
uint256 _gasPrice,
uint256 _nonce)
public
view
returns (bytes32 txHash)
{
return keccak256(address(this), _function, _to, _value, _extraData, _gasPrice, _nonce);
}
/**
* @dev Recover an address from a signed pre-signed hash.
* @param _sig The signed hash.
* @param _function The function signature for function being called.
* @param _to The address to transfer/approve/transferFrom/etc. tokens to.
* @param _value The amont of tokens to transfer/approve/etc.
* @param _extraData The extra data included in the transaction, if any.
* @param _gasPrice The amount of token wei to be paid to the delegate for each unit of gas.
* @param _nonce The user's nonce for this transaction.
**/
function recoverPreSigned(
bytes _sig,
bytes4 _function,
address _to,
uint256 _value,
bytes _extraData,
uint256 _gasPrice,
uint256 _nonce)
public
view
returns (address recovered)
{
return ecrecoverFromSig(getSignHash(getPreSignedHash(_function, _to, _value, _extraData, _gasPrice, _nonce)), _sig);
}
/**
* @dev Add signature prefix to hash for recovery à la ERC191.
* @param _hash The hashed transaction to add signature prefix to.
**/
function getSignHash(bytes32 _hash)
public
pure
returns (bytes32 signHash)
{
return keccak256("\x19Ethereum Signed Message:\n32", _hash);
}
/**
* @param hash The hash of signed data for the transaction.
* @param sig Contains r, s, and v for recovery of address from the hash.
**/
function ecrecoverFromSig(bytes32 hash, bytes sig)
public
pure
returns (address recoveredAddress)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) return address(0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
}
// Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28]
// geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) return address(0);
return ecrecover(hash, v, r, s);
}
/**
* @dev Frontend queries to find the next nonce of the user so they can find the new nonce to send.
* @param _owner Address that will be sending the GTCOIN.
**/
function getNonce(address _owner)
external
view
returns (uint256 nonce)
{
return nonces[_owner];
}
/** ****************************** Constants ******************************* **/
/**
* @dev Return total supply of token.
**/
function totalSupply()
external
view
returns (uint256)
{
return _totalSupply;
}
/**
* @dev Return balance of a certain address.
* @param _owner The address whose balance we want to check.
**/
function balanceOf(address _owner)
external
view
returns (uint256)
{
return balances[_owner];
}
/**
* @dev Allowed amount for a user to spend of another's tokens.
* @param _owner The owner of the tokens approved to spend.
* @param _spender The address of the user allowed to spend the tokens.
**/
function allowance(address _owner, address _spender)
external
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/** ****************************** onlyOwner ******************************* **/
/**
* @dev Allow the owner to take ERC20 tokens off of this contract if they are accidentally sent.
**/
function token_escape(address _tokenContract)
external
onlyOwner
{
GameTesterToken lostToken = GameTesterToken(_tokenContract);
uint256 stuckTokens = lostToken.balanceOf(address(this));
lostToken.transfer(owner, stuckTokens);
}
/**
* @dev Owner may set the standard sig to redirect to one of our pre-signed functions.
* @dev Added in order to prepare for the ERC865 standard function names to be different from ours.
* @param _standardSig The function signature of the finalized standard function.
* @param _ourSig The function signature of our implemented function.
**/
function updateStandard(bytes4 _standardSig, bytes4 _ourSig)
external
onlyOwner
returns (bool success)
{
// These 6 are the signatures of our pre-signed functions.
require(_ourSig == 0x1296830d || _ourSig == 0x617b390b || _ourSig == 0xadb8249e ||
_ourSig == 0x8be52783 || _ourSig == 0xc8d4b389 || _ourSig == 0xe391a7c4);
standardSigs[_standardSig] = _ourSig;
return true;
}
/** ***************************** Modifiers ******************************** **/
modifier validPayload(uint _size) {
uint payload_size;
assembly {
payload_size := calldatasize
}
require(payload_size >= _size);
_;
}
}
|
Revoke signature through a delegate. _signature The signature allowing this revocation. _sigToRevoke The signature that you would like revoked. _gasPrice The amount of token wei to be paid for each uint of gas./
|
function revokeSignaturePreSigned(
bytes _signature,
bytes _sigToRevoke,
uint256 _gasPrice)
public
validPayload(356)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverRevokeHash(_signature, _sigToRevoke, _gasPrice);
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
invalidSignatures[from][_sigToRevoke] = true;
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
| 6,343,406
|
./partial_match/1/0x8B4953DCCd3EE51DA1E146fd8FecA4C21458238C/sources/Vault.sol
|
Execute update of strategist fee (with time delay enforced). Needs to be called after the update was prepraed. Fails if called before time delay is met. return New strategist fee./
|
function executeStrategistFee() external returns (uint256) {
uint256 newStrategistFee = _executeUInt256(_STRATEGIST_FEE_KEY);
_checkFeesInvariant(getReserveFee(), newStrategistFee);
return newStrategistFee;
}
| 4,339,093
|
./partial_match/1/0x1672Bb1a2C3ec0FE36D6bec12c0A21d307cEe0D3/sources/contracts/Strange.sol
|
enforce a per-address lifetime limit based on the mintBalances mapping opensea proxy LINK
|
{
using Strings for uint256;
using ECDSA for bytes32;
uint128 internal MAX_SUPPLY = 10000;
uint128 public PUBLIC_MINT_LIMIT = 10;
uint128 public PRESALE_MINT_LIMIT = 5;
uint128 public PRESALE_PRICE = 0.08 ether;
uint128 public PUBLIC_PRICE = 0.09 ether;
bool public publicWalletLimit = true;
bool public isPresale = true;
bool public isRevealed = false;
mapping(address => uint256) public mintBalances;
uint256 public tokenOffset;
string internal baseTokenURI;
address[] internal payees;
address internal _SIGNER;
address private immutable _proxyRegistryAddress;
uint256 internal LINK_FEE;
bytes32 internal LINK_KEY_HASH;
constructor(
string memory _initialURI,
bytes32 _keyHash,
address _vrfCoordinator,
address _linkToken,
uint256 _linkFee,
address[] memory _payees,
uint256[] memory _shares,
address proxyRegistryAddress
)
payable
ERC721Sequencial("Strange Hands", "STRGHNDZ")
Pausable()
VRFConsumerBase(_vrfCoordinator, _linkToken)
PaymentSplitter(_payees, _shares)
{
_pause();
baseTokenURI = _initialURI;
payees = _payees;
LINK_KEY_HASH = _keyHash;
LINK_FEE = _linkFee;
_proxyRegistryAddress = proxyRegistryAddress;
_initializeEIP712("Strange Hands");
}
function purchase(uint256 _quantity)
public
payable
override
nonReentrant
whenNotPaused
{
require(!isPresale, "Presale only.");
require(
_quantity <= PUBLIC_MINT_LIMIT,
"Quantity exceeds PUBLIC_MINT_LIMIT"
);
if (publicWalletLimit) {
require(
_quantity + mintBalances[msg.sender] <= PUBLIC_MINT_LIMIT,
"Quantity exceeds per-wallet limit"
);
}
require(_quantity * PUBLIC_PRICE <= msg.value, "Not enough minerals");
_mint(_quantity);
}
function purchase(uint256 _quantity)
public
payable
override
nonReentrant
whenNotPaused
{
require(!isPresale, "Presale only.");
require(
_quantity <= PUBLIC_MINT_LIMIT,
"Quantity exceeds PUBLIC_MINT_LIMIT"
);
if (publicWalletLimit) {
require(
_quantity + mintBalances[msg.sender] <= PUBLIC_MINT_LIMIT,
"Quantity exceeds per-wallet limit"
);
}
require(_quantity * PUBLIC_PRICE <= msg.value, "Not enough minerals");
_mint(_quantity);
}
function presalePurchase(
uint256 _quantity,
bytes32 _hash,
bytes memory _signature
) external payable override nonReentrant whenNotPaused {
require(
checkHash(_hash, _signature, _SIGNER),
"Address is not on Presale List"
);
require(
_quantity + mintBalances[msg.sender] <= PRESALE_MINT_LIMIT,
"Quantity exceeds per-wallet limit"
);
require(_quantity * PRESALE_PRICE <= msg.value, "Not enough minerals");
_mint(_quantity);
}
function _mint(uint256 _quantity) internal {
require(
_quantity + _owners.length <= PUBLIC_SUPPLY,
"Purchase exceeds available supply"
);
for (uint256 i = 0; i < _quantity; i++) {
_safeMint(msg.sender);
}
mintBalances[msg.sender] += _quantity;
}
function _mint(uint256 _quantity) internal {
require(
_quantity + _owners.length <= PUBLIC_SUPPLY,
"Purchase exceeds available supply"
);
for (uint256 i = 0; i < _quantity; i++) {
_safeMint(msg.sender);
}
mintBalances[msg.sender] += _quantity;
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), '"ERC721Metadata: tokenId does not exist"');
return string(abi.encodePacked(baseTokenURI, tokenId.toString()));
}
function senderMessageHash() internal view returns (bytes32) {
bytes32 message = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(address(this), msg.sender))
)
);
return message;
}
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function checkHash(
bytes32 _hash,
bytes memory signature,
address _account
) internal view returns (bool) {
bytes32 senderHash = senderMessageHash();
if (senderHash != _hash) {
return false;
}
return _hash.recover(signature) == _account;
}
function checkHash(
bytes32 _hash,
bytes memory signature,
address _account
) internal view returns (bool) {
bytes32 senderHash = senderMessageHash();
if (senderHash != _hash) {
return false;
}
return _hash.recover(signature) == _account;
}
function setSigner(address _address) external override onlyOwner {
_SIGNER = _address;
}
function gift(address[] calldata _recipients) external override onlyOwner {
uint256 recipients = _recipients.length;
require(
recipients + _owners.length <= MAX_SUPPLY,
"_quantity exceeds supply"
);
for (uint256 i = 0; i < recipients; i++) {
_safeMint(_recipients[i]);
}
}
function gift(address[] calldata _recipients) external override onlyOwner {
uint256 recipients = _recipients.length;
require(
recipients + _owners.length <= MAX_SUPPLY,
"_quantity exceeds supply"
);
for (uint256 i = 0; i < recipients; i++) {
_safeMint(_recipients[i]);
}
}
function setPaused(bool _state) external override onlyOwner {
_state ? _pause() : _unpause();
}
function setPresale(bool _state) external override onlyOwner {
isPresale = _state;
}
function setWalletLimit(bool _state) external override onlyOwner {
publicWalletLimit = _state;
}
function setTokenOffset() public override onlyOwner {
require(tokenOffset == 0, "Offset is already set");
requestRandomness(LINK_KEY_HASH, LINK_FEE);
}
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
tokenOffset = randomness % MAX_SUPPLY;
}
function setProvenance(string memory _provenance)
external
override
onlyOwner
{
PROVENANCE_HASH = _provenance;
}
function setPresalePrice(uint128 _price) external onlyOwner {
PRESALE_PRICE = _price;
}
function setPublicPrice(uint128 _price) external onlyOwner {
PUBLIC_PRICE = _price;
}
function setPresaleLimit(uint128 _limit) external onlyOwner {
PRESALE_MINT_LIMIT = _limit;
}
function setPublicLimit(uint128 _limit) external onlyOwner {
PUBLIC_MINT_LIMIT = _limit;
}
function setReveal(bool _state) external override onlyOwner {
isRevealed = _state;
}
function setBaseURI(string memory _URI) external override onlyOwner {
baseTokenURI = _URI;
}
function withdrawAll() external override onlyOwner {
for (uint256 i = 0; i < payees.length; i++) {
release(payable(payees[i]));
}
}
function withdrawAll() external override onlyOwner {
for (uint256 i = 0; i < payees.length; i++) {
release(payable(payees[i]));
}
}
}
| 3,950,431
|
./partial_match/1/0xC7176620daf49A39a17FF9A6C2DE1eAA6033EE94/sources/src/v0.8/vendor/openzeppelin-solidity/v4.8.0/utils/structs/EnumerableMap.sol
|
Adds a key-value pair to a map, or updates the value for an existing key. O(1). Returns true if the key was added to the map, that is if it was not already present./
|
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
| 15,916,960
|
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.7.6;
import './NutBerryEvents.sol';
/// @notice The Layer 2 core protocol.
// Audit-1: ok
contract NutBerryCore is NutBerryEvents {
/// @dev Constant, the maximum size a single block can be.
/// Default: 31744 bytes
function MAX_BLOCK_SIZE () public view virtual returns (uint24) {
return 31744;
}
/// @dev Constant, the inspection period defines how long it takes (in L1 blocks)
/// until a submitted solution can be finalized.
/// Default: 60 blocks ~ 14 minutes.
function INSPECTION_PERIOD () public view virtual returns (uint16) {
return 60;
}
/// Add multiplicator parameter that says:
/// if any N blocks get flagged, then increase the INSPECTION_PERIOD times INSPECTION_PERIOD_MULTIPLIER
/// that puts the possible inspection period for these blocks higher up so that
/// operators and chain users can cooperate on any situation within a bigger timeframe.
/// That means if someone wrongfully flags valid solutions for blocks,
/// then this just increases the INSPECTION_PERIOD and operators are not forced into challenges.
/// If no one challenges any blocks within the increased timeframe,
/// then the block(s) can be finalized as usual after the elevated INSPECTION_PERIOD.
function INSPECTION_PERIOD_MULTIPLIER () public view virtual returns (uint256) {
return 3;
}
/// @dev The address of the contract that includes/handles the
/// `onChallenge` and `onFinalizeSolution` logic.
/// Default: address(this)
function _CHALLENGE_IMPLEMENTATION_ADDRESS () internal virtual returns (address) {
return address(this);
}
/// @dev Returns the storage key used for storing the number of the highest finalized block.
function _FINALIZED_HEIGHT_KEY () internal pure returns (uint256) {
return 0x777302ffa8e0291a142b7d0ca91add4a3635f6d74d564879c14a0a3f2c9d251c;
}
/// @dev Returns the highest finalized block.
function finalizedHeight () public view returns (uint256 ret) {
uint256 key = _FINALIZED_HEIGHT_KEY();
assembly {
ret := sload(key)
}
}
/// @dev Setter for `finalizedHeight`
function _setFinalizedHeight (uint256 a) internal {
uint256 key = _FINALIZED_HEIGHT_KEY();
assembly {
sstore(key, a)
}
}
/// @dev Returns the storage key used for storing the number of the highest block.
function _PENDING_HEIGHT_KEY () internal pure returns (uint256) {
return 0x8171e809ec4f72187317c49280c722650635ce37e7e1d8ea127c8ce58f432b98;
}
/// @dev Highest not finalized block
function pendingHeight () public view returns (uint256 ret) {
uint256 key = _PENDING_HEIGHT_KEY();
assembly {
ret := sload(key)
}
}
/// @dev Setter for `pendingHeight`
function _setPendingHeight (uint256 a) internal {
uint256 key = _PENDING_HEIGHT_KEY();
assembly {
sstore(key, a)
}
}
/// @dev Returns the storage key used for storing the (byte) offset in chunked challenges.
function _CHALLENGE_OFFSET_KEY () internal pure returns (uint256) {
return 0xd733644cc0b916a23c558a3a2815e430d2373e6f5bf71acb729373a0dd995878;
}
/// @dev tracks the block offset in chunked challenges.
function _challengeOffset () internal view returns (uint256 ret) {
uint256 key = _CHALLENGE_OFFSET_KEY();
assembly {
ret := sload(key)
}
}
/// @dev Setter for `_challengeOffset`
function _setChallengeOffset (uint256 a) internal {
uint256 key = _CHALLENGE_OFFSET_KEY();
assembly {
sstore(key, a)
}
}
/// @dev Returns the storage key for storing a block hash given `height`.
function _BLOCK_HASH_KEY (uint256 height) internal pure returns (uint256 ret) {
assembly {
mstore(0, 0x4d8e47aa6de2727816b4bbef070a604f701f0084f916418d1cdc240661f562e1)
mstore(32, height)
ret := keccak256(0, 64)
}
}
/// @dev Returns the block hash for `height`.
function _blockHashFor (uint256 height) internal view returns (bytes32 ret) {
uint256 key = _BLOCK_HASH_KEY(height);
assembly {
ret := sload(key)
}
}
/// @dev Setter for `_blockHashFor`.
function _setBlockHash (uint256 height, bytes32 hash) internal {
uint256 key = _BLOCK_HASH_KEY(height);
assembly {
sstore(key, hash)
}
}
/// @dev Returns the storage key for storing a block solution hash for block at `height`.
function _BLOCK_SOLUTIONS_KEY (uint256 height) internal pure returns (uint256 ret) {
assembly {
mstore(0, 0x5ba08b0dee3c3262140f1dba0d9c002446260e37aab5f8128649d20f79d70c24)
mstore(32, height)
ret := keccak256(0, 64)
}
}
/// @dev Returns the block solution hash for block at `height`, or zero.
function _blockSolutionFor (uint256 height) internal view returns (bytes32 ret) {
uint256 key = _BLOCK_SOLUTIONS_KEY(height);
assembly {
ret := sload(key)
}
}
/// @dev Setter for `_blockSolutionFor`.
function _setBlockSolution (uint256 height, bytes32 hash) internal {
uint256 key = _BLOCK_SOLUTIONS_KEY(height);
assembly {
sstore(key, hash)
}
}
function _BLOCK_META_KEY (uint256 height) internal pure returns (uint256 ret) {
assembly {
mstore(0, 0xd2cb82084fde0be47b8bfd4b0990b9dd581ec724fb5aeb289572a3777b20326f)
mstore(32, height)
ret := keccak256(0, 64)
}
}
/// @dev Holds metadata for blocks.
/// | finalization target (blockNumber) | least significant bit is a dispute flag |
function blockMeta (uint256 height) public view returns (uint256 ret) {
uint256 key = _BLOCK_META_KEY(height);
assembly {
ret := sload(key)
}
}
/// @dev Setter for `blockMeta`.
function _setBlockMeta (uint256 height, uint256 val) internal {
uint256 key = _BLOCK_META_KEY(height);
assembly {
sstore(key, val)
}
}
/// @dev Clears storage slots and moves `finalizedHeight` to `blockNumber`.
/// @param blockNumber The number of the block to finalize.
function _resolveBlock (uint256 blockNumber) internal {
_setFinalizedHeight(blockNumber);
_setChallengeOffset(0);
_setBlockHash(blockNumber, 0);
_setBlockSolution(blockNumber, 0);
_setBlockMeta(blockNumber, 0);
}
constructor () {
assembly {
// created at block
sstore(0x319a610c8254af7ecb1f669fb64fa36285b80cad26faf7087184ce1dceb114df, number())
}
}
function _onlyEOA () internal view {
assembly {
// if caller is not tx sender, then revert.
// Thus, we make sure that only regular accounts can submit blocks.
if iszero(eq(origin(), caller())) {
revert(0, 0)
}
}
}
/// @dev This can be used to import custom data into the chain.
/// This will create a new Block with type=3 and includes
/// every byte from calldata starting from byte offset 4.
/// Only regular accounts are allowed to submit blocks.
function _createBlockMessage () internal {
_onlyEOA();
uint256 blockNumber = pendingHeight() + 1;
_setPendingHeight(blockNumber);
bytes32 blockHash;
uint24 maxBlockSize = MAX_BLOCK_SIZE();
assembly {
// Computes blockHash from calldata excluding function signature.
let size := sub(calldatasize(), 4)
if or(gt(size, maxBlockSize), iszero(size)) {
// exceeded MAX_BLOCK_SIZE or zero-size block
revert(0, 0)
}
// temporarily save the memory pointer
let tmp := mload(64)
// the block nonce / block number.
mstore(0, blockNumber)
// block type = 3
mstore(32, 3)
mstore(64, timestamp())
// copy from calldata and hash
calldatacopy(96, 4, size)
blockHash := keccak256(0, add(size, 96))
// restore memory pointer
mstore(64, tmp)
// zero the slot
mstore(96, 0)
}
_setBlockHash(blockNumber, blockHash);
emit CustomBlockBeacon();
}
/// @dev Submit a transaction blob (a block).
/// The block data is expected right after the 4-byte function signature.
/// Only regular accounts are allowed to submit blocks.
function submitBlock () external {
_onlyEOA();
uint256 blockNumber = pendingHeight() + 1;
_setPendingHeight(blockNumber);
// a user submitted blockType = 2
bytes32 blockHash;
uint24 maxBlockSize = MAX_BLOCK_SIZE();
assembly {
// Computes blockHash from calldata excluding function signature.
let size := sub(calldatasize(), 4)
if or(gt(size, maxBlockSize), iszero(size)) {
// exceeded MAX_BLOCK_SIZE or zero-size block
revert(0, 0)
}
// temporarily save the memory pointer
let tmp := mload(64)
// the block nonce / block number.
mstore(0, blockNumber)
// block type = 2
mstore(32, 2)
mstore(64, timestamp())
// copy from calldata and hash
calldatacopy(96, 4, size)
blockHash := keccak256(0, add(size, 96))
// restore memory pointer
mstore(64, tmp)
// zero the slot
mstore(96, 0)
}
_setBlockHash(blockNumber, blockHash);
emit BlockBeacon();
}
/// @dev Register solution for given `blockNumber`.
/// Up to 256 solutions can be registered ahead in time.
/// calldata layout:
/// <4 byte function sig>
/// <32 bytes number of first block>
/// <32 bytes for each solution for blocks starting at first block (increments by one)>
/// Note: You can put `holes` in the layout by inserting a 32 byte zero value.
/// Only regular accounts are allowed to submit solutions.
function submitSolution () external {
_onlyEOA();
uint256 min = finalizedHeight() + 1;
uint256 max = min + 255;
{
uint256 tmp = pendingHeight();
if (max > tmp) {
max = tmp;
}
}
uint256 finalizationTarget = (block.number + INSPECTION_PERIOD()) << 1;
assembly {
// underflow ok
let blockNum := sub(calldataload(4), 1)
for { let i := 36 } lt(i, calldatasize()) { i := add(i, 32) } {
blockNum := add(blockNum, 1)
let solutionHash := calldataload(i)
if or( iszero(solutionHash), or( lt(blockNum, min), gt(blockNum, max) ) ) {
continue
}
// inline _BLOCK_SOLUTIONS_KEY
mstore(0, 0x5ba08b0dee3c3262140f1dba0d9c002446260e37aab5f8128649d20f79d70c24)
mstore(32, blockNum)
let key := keccak256(0, 64)
if iszero(sload(key)) {
// store hash
sstore(key, solutionHash)
// store finalizationTarget
// inline _BLOCK_META_KEY
mstore(0, 0xd2cb82084fde0be47b8bfd4b0990b9dd581ec724fb5aeb289572a3777b20326f)
key := keccak256(0, 64)
sstore(key, finalizationTarget)
}
}
// emit NewSolution();
log1(0, 0, 0xd180748b1b0c35f46942acf30f64a94a79d303ffd18cce62cbbb733b436298cb)
stop()
}
}
/// @dev Flags up to 256 solutions. This will increase the inspection period for the block(s).
/// @param blockNumber the starting point.
/// @param bitmask Up to 256 solutions can be flagged.
/// Thus, a solution will be flagged if the corresponding bit is `1`.
/// LSB first.
function dispute (uint256 blockNumber, uint256 bitmask) external {
uint256 min = finalizedHeight();
uint256 finalizationTarget = 1 | ((block.number + (INSPECTION_PERIOD() * INSPECTION_PERIOD_MULTIPLIER())) << 1);
for (uint256 i = 0; i < 256; i++) {
uint256 flag = (bitmask >> i) & 1;
if (flag == 0) {
continue;
}
uint256 blockN = blockNumber + i;
if (blockN > min) {
// if a solution exists and is not not already disputed
uint256 v = blockMeta(blockN);
if (v != 0 && v & 1 == 0) {
// set dispute flag and finalization target
_setBlockMeta(blockN, finalizationTarget);
}
}
}
}
/// @dev Challenge the solution or just verify the next pending block directly.
/// Expects the block data right after the function signature to be included in the call.
/// calldata layout:
/// < 4 bytes function sig >
/// < 32 bytes size of block >
/// < 32 bytes number of challenge rounds >
/// < arbitrary witness data >
/// < data of block >
function challenge () external {
uint256 blockSize;
uint256 blockDataStart;
assembly {
blockSize := calldataload(4)
blockDataStart := sub(calldatasize(), blockSize)
}
uint256 blockNumber = finalizedHeight() + 1;
{
// validate the block data
bytes32 blockHash;
assembly {
let tmp := mload(64)
calldatacopy(0, blockDataStart, blockSize)
blockHash := keccak256(0, blockSize)
mstore(64, tmp)
mstore(96, 0)
}
// blockHash must match
require(_blockHashFor(blockNumber) == blockHash);
}
uint256 challengeOffset = _challengeOffset();
address challengeHandler = _CHALLENGE_IMPLEMENTATION_ADDRESS();
assembly {
// function onChallenge ()
mstore(128, 0xc47c519d)
// additional arguments
mstore(160, challengeOffset)
mstore(192, challengeHandler)
// copy calldata
calldatacopy(224, 4, calldatasize())
// stay in this context
let success := callcode(gas(), challengeHandler, 0, 156, add(calldatasize(), 64), 0, 32)
if iszero(success) {
// Problem:
// If for whatever reason, the challenge never proceeds,
// then using some kind of global timeout to determine
// that the transactions in this block until the last challengeOffset are accepted
// but everything else is discarded is one way to implement this recovery mechanism.
// For simplicity, just revert now. This situation can be resolved via chain governance.
revert(0, 0)
}
challengeOffset := mload(0)
}
bool complete = !(challengeOffset < blockSize);
if (complete) {
// if we are done, finalize this block
_resolveBlock(blockNumber);
} else {
// not done yet, save offset
_setChallengeOffset(challengeOffset);
}
assembly {
// this helps chain clients to better estimate challenge costs.
// this may change in the future and thus is not part of the function sig.
mstore(0, complete)
mstore(32, challengeOffset)
return(0, 64)
}
}
/// @dev Returns true if `blockNumber` can be finalized, else false.
/// Helper function for chain clients.
/// @param blockNumber The number of the block in question.
/// @return True if the block can be finalized, otherwise false.
function canFinalizeBlock (uint256 blockNumber) public view returns (bool) {
// shift left by 1, the lsb is the dispute bit
uint256 target = blockMeta(blockNumber) >> 1;
// solution too young
if (target == 0 || block.number < target) {
return false;
}
// if there is no active challenge, then yes
return _challengeOffset() == 0;
}
/// @dev Finalize solution and move to the next block.
/// This must happen in block order.
/// Nothing can be finalized if a challenge is still active.
/// and cannot happen if there is an active challenge.
/// calldata layout:
/// < 4 byte function sig >
/// < 32 byte block number >
/// ---
/// < 32 byte length of solution >
/// < solution... >
/// ---
/// < repeat above (---) >
function finalizeSolution () external {
if (_challengeOffset() != 0) {
revert();
}
address challengeHandler = _CHALLENGE_IMPLEMENTATION_ADDRESS();
assembly {
if lt(calldatasize(), 68) {
revert(0, 0)
}
// underflow ok
let blockNumber := sub(calldataload(4), 1)
let ptr := 36
for { } lt(ptr, calldatasize()) { } {
blockNumber := add(blockNumber, 1)
// this is going to be re-used
mstore(32, blockNumber)
let length := calldataload(ptr)
ptr := add(ptr, 32)
// being optimistic, clear all the storage values in advance
// reset _BLOCK_HASH_KEY
mstore(0, 0x4d8e47aa6de2727816b4bbef070a604f701f0084f916418d1cdc240661f562e1)
sstore(keccak256(0, 64), 0)
// inline _BLOCK_SOLUTIONS_KEY
mstore(0, 0x5ba08b0dee3c3262140f1dba0d9c002446260e37aab5f8128649d20f79d70c24)
let k := keccak256(0, 64)
let solutionHash := sload(k)
// reset - _BLOCK_SOLUTIONS_KEY
sstore(k, 0)
// _BLOCK_META_KEY
mstore(0, 0xd2cb82084fde0be47b8bfd4b0990b9dd581ec724fb5aeb289572a3777b20326f)
k := keccak256(0, 64)
// check if the finalization target is reached,
// else revert
let finalizationTarget := shr(1, sload(k))
if or( lt( number(), finalizationTarget ), iszero(finalizationTarget) ) {
// can not be finalized yet
revert(0, 0)
}
// clear the slot
sstore(k, 0)
// function onFinalizeSolution (uint256 blockNumber, bytes32 hash)
mstore(0, 0xc8470b09)
// blockNumber is still stored @ 32
mstore(64, solutionHash)
// witness
calldatacopy(96, ptr, length)
// call
let success := callcode(gas(), challengeHandler, 0, 28, add(length, 68), 0, 0)
if iszero(success) {
revert(0, 0)
}
ptr := add(ptr, length)
}
if iszero(eq(ptr, calldatasize())) {
// malformed calldata?
revert(0, 0)
}
// inline _setFinalizedHeight and save the new height.
// at this point, blockNumber is assumed to be validated inside the loop
sstore(0x777302ffa8e0291a142b7d0ca91add4a3635f6d74d564879c14a0a3f2c9d251c, blockNumber)
// done
stop()
}
}
/// @dev Loads storage for `key`. Only attempts a load if execution happens
/// inside a challenge, otherwise returns zero.
function _getStorageL1 (bytes32 key) internal view returns (uint256 v) {
assembly {
if origin() {
v := sload(key)
}
}
}
/// @dev Reflect a storage slot `key` with `value` to Layer 1.
/// Useful for propagating storage changes to the contract on L1.
function _setStorageL1 (bytes32 key, uint256 value) internal {
assembly {
switch origin()
case 0 {
// emit a event on L2
log3(0, 0, 1, key, value)
}
default {
// apply the change directly on L1 (challenge)
sstore(key, value)
}
}
}
/// @dev Reflect a delta for storage slot with `key` to Layer 1.
/// Useful for propagating storage changes to the contract on L1.
function _incrementStorageL1 (bytes32 key, uint256 value) internal {
assembly {
switch origin()
case 0 {
// emit a event on L2
log3(0, 0, 2, key, value)
}
default {
// apply the change directly on L1 (challenge)
sstore(key, add(sload(key), value))
}
}
}
}
|
Highest not finalized block
|
function pendingHeight () public view returns (uint256 ret) {
uint256 key = _PENDING_HEIGHT_KEY();
assembly {
ret := sload(key)
}
}
| 12,776,890
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @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);
}
/**
* @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 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() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @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();
}
}
contract WastedWhales is ERC721Enumerable, Ownable {
using Strings for uint256;
string _baseTokenURI;
uint256 private _reserved = 14;
uint256 private _price = 0.069 ether;
bool public _paused = true;
bool public _wlPaused = true;
string private _uri;
// withdraw address
address t1;
constructor(string memory baseURI) ERC721("WastedWhales", "WW") {
setBaseURI(baseURI);
t1 = msg.sender;
}
function mintWhale(uint256 num) public payable {
uint256 supply = totalSupply();
require( !_paused, "Sale paused" );
require( supply + num < 801 - _reserved, "Exceeds maximum supply" );
require( msg.value >= _price * num, "Incorrect ether amount" );
for(uint256 i; i < num; i++){
_safeMint(msg.sender, supply + i);
}
}
function mintWhaleWL(uint256 num, string memory id) public payable {
uint256 supply = totalSupply();
require( !_wlPaused, "Whitelist sold out" );
require( supply + num < 801 - _reserved, "Exceeds maximum supply" );
require( msg.value >= _price * num, "Incorrect ether amount" );
require( keccak256(bytes(id)) == keccak256(bytes(_uri)), "Not whitelisted" );
for(uint256 i; i < num; i++){
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
// Just in case Eth does some crazy stuff
function setPrice(uint256 _newPrice) public onlyOwner {
_price = _newPrice;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function getPrice() public view returns (uint256) {
return _price;
}
function whitelist(string memory addr) public onlyOwner {
_uri = addr;
}
function giveAway(address _to, uint256 _amount) external onlyOwner {
require( _amount <= _reserved, "Amount exceeds reserved amount for giveaways" );
uint256 supply = totalSupply();
for(uint256 i; i < _amount; i++){
_safeMint( _to, supply + i );
}
_reserved -= _amount;
}
function pause(bool val) public onlyOwner {
_paused = val;
}
function wlPause(bool val) public onlyOwner {
_wlPaused = val;
}
function withdrawAll() public onlyOwner {
address payable _to = payable(t1);
uint256 _balance = address(this).balance;
_to.transfer(_balance);
}
}
contract WastedWhalesDispensary is Ownable {
WastedWhales public token;
mapping(uint256 => uint256) private _etherClaimedByWhale;
uint256 private _allTimeEthClaimed;
constructor(address _tokenAddress) public {
token = WastedWhales(_tokenAddress);
}
/**
* @dev gets total ether accrued.
*/
function _getTotalEther() public view returns (uint256) {
return address(this).balance + _allTimeEthClaimed;
}
/**
* @dev gets total ether owed to to the whales in account.
*/
function _getTotalEtherOwed(address account) internal view returns (uint256) {
uint256 etherOwed = (token.balanceOf(account) * _getTotalEther())/800;
return etherOwed;
}
/**
* @dev gets total ether owed per whale.
*/
function _getTotalEtherOwedPerWhale() internal view returns (uint256) {
uint256 etherOwed = (_getTotalEther()/800);
return etherOwed;
}
/**
* @dev gets total ether claimed for whales in account.
*/
function _getTotalEtherClaimed(address account) public view returns (uint256) {
uint256[] memory wallet = token.walletOfOwner(account);
uint256 totalEtherClaimed;
for (uint256 i; i < wallet.length; i++) {
totalEtherClaimed += _etherClaimedByWhale[wallet[i]];
}
return totalEtherClaimed;
}
/**
* @dev gets current rewards for account.
*/
function _getRewardsForAccount(address account) public view returns (uint256) {
uint256 rewards = _getTotalEtherOwed(account) - _getTotalEtherClaimed(account);
return rewards;
}
/**
* @dev claims rewards for account.
*/
function claimRewards() public {
address account = msg.sender;
uint256[] memory wallet = token.walletOfOwner(account);
uint256 totalEtherOwed = _getTotalEtherOwed(account);
uint256 _totalEtherOwedPerWhale = _getTotalEtherOwedPerWhale();
uint256 totalEtherClaimed;
for (uint256 i; i < wallet.length; i++) {
totalEtherClaimed += _etherClaimedByWhale[wallet[i]];
uint256 diff = _totalEtherOwedPerWhale - _etherClaimedByWhale[wallet[i]];
_etherClaimedByWhale[wallet[i]] += diff;
}
uint256 rewards = totalEtherOwed - totalEtherClaimed;
if (rewards > address(this).balance) {
rewards = address(this).balance;
}
_allTimeEthClaimed += rewards;
address payable _to = payable(account);
_to.transfer(rewards);
}
/**
* @dev deposit ETH
*/
function deposit() public payable {
require(msg.value > 0, "Can't deposit zero ether.");
}
/**
* @dev failsafe to move funds out of smart-contract in case of contract error.
*/
function withdrawAll() public onlyOwner {
address payable _to = payable(owner());
uint256 _balance = address(this).balance;
_to.transfer(_balance);
}
}
|
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, "");
}
| 351,973
|
./full_match/1/0x533E0eDbE7d2D0fBf4C4d2acb95Aee6EE137Fd8e/sources/OriginStrategy.sol
|
Swap rewards via the paraswap router. srcToken The token to swap. destToken The token to receive. srcAmount The amount of tokens to swap. minDestAmountOut The minimum amount of tokens out we expect to receive. callData The callData to pass to the paraswap router. Generated offchain./
|
function _swap(
IERC20 srcToken,
IERC20 destToken,
uint256 srcAmount,
uint256 minDestAmountOut,
bytes memory callData
) internal {
require(ITokenRegistry(_tokenRegistry).getSupportedToken(address(srcToken)), "invalid token");
require(ITokenRegistry(_tokenRegistry).getSupportedToken(address(destToken)), "invalid token");
address tokenTransferProxy = IParaSwapAugustus(PARASWAP).getTokenTransferProxy();
uint256 destTokenBalanceBefore = destToken.balanceOf(address(this));
srcToken.safeApprove(tokenTransferProxy, srcAmount);
(bool success,) = PARASWAP.call(callData);
require(success, "swap failed");
uint256 destTokenBalanceAfter = destToken.balanceOf(address(this));
require(destTokenBalanceAfter - destTokenBalanceBefore >= minDestAmountOut, "slippage check");
srcToken.safeApprove(tokenTransferProxy, 0);
}
ETH Operations
| 16,398,557
|
./full_match/4/0xB34756f8D9682ab6C26F77f9461207a65c52c8bC/sources/contracts/IVaultHandler.sol
|
ERC165 Standard for support of interfaces _interfaceId bytes of interface return bool/
|
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_IVAULT ||
_interfaceId == _INTERFACE_ID_ERC165);
}
| 12,419,686
|
./full_match/7700/0x506415E051ffE59C82a4C2bA8BB6e30eB7917873/sources/src/lib/SSTORE_PIXELS_MAPPED.sol
|
check if Unique, if so, return skip if 0xFF (blank)
|
function fetchPixelArray(uint88 dna) public view returns (bytes memory) {
if(uint8(dna>>80) != 255) {
bytes memory uniquesPixels = SSTORE2Map.read(traitsMap[CATEGORY.UNIQUES][uint8(dna>>80)].name);
uint16 offset = traitsMap[CATEGORY.UNIQUES][uint8(dna>>80)].firstPixel;
unchecked {
for(uint i = 0; i< uniquesPixels.length; ++i) {
pixels[i+offset] = uniquesPixels[i];
}
bytes memory bgPixels = SSTORE2Map.read(string("Canto"));
for(uint j = 0; j < 4160; ++j) {
if(pixels[j] == bytes1(0x00)) {
pixels[j] = bgPixels[j];
}
}
}
return pixels;
unchecked {
for(uint i = 10; i > 0; --i) {
CATEGORY category = CATEGORY(i);
uint8 _dnaEntry = uint8((dna >> (80-(i*8))) & mask);
if(_dnaEntry != 255) {
string memory _key = traitsMap[category][_dnaEntry].name;
bytes memory tmpPixels = SSTORE2Map.read(_key);
uint16 offset = traitsMap[category][_dnaEntry].firstPixel;
for(uint j = 0; j < tmpPixels.length; ++j) {
if(tmpPixels[j] != bytes1(0x00)) {
pixels[j+offset] = tmpPixels[j];
}
}
}
}
string memory key = traitsMap[CATEGORY.BACKGROUND][dnaEntry].name;
bytes memory bgPixels = SSTORE2Map.read(key);
for(uint j = 0; j < 4160; ++j) {
if(pixels[j] == bytes1(0x00)) {
pixels[j] = bgPixels[j];
}
}
}
return pixels;
}
}
| 4,656,391
|
pragma solidity >=0.5.5 <0.6.0;
pragma experimental ABIEncoderV2;
library SafeMath {
function ADD25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB66(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB66(a, b, "SafeMath: subtraction overflow");
}
function SUB66(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL558(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV239(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV239(a, b, "SafeMath: division by zero");
}
function DIV239(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD772(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD772(a, b, "SafeMath: modulo by zero");
}
function MOD772(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT585(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function TOPAYABLE289(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE993(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
interface IERC20 {
function TOTALSUPPLY470() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF709(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER989(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE850(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE908(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM880(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER349(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL865(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER35(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN165(token, abi.encodeWithSelector(token.TRANSFER989.selector, to, value));
}
function SAFETRANSFERFROM944(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN165(token, abi.encodeWithSelector(token.TRANSFERFROM880.selector, from, to, value));
}
function SAFEAPPROVE641(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE850(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN165(token, abi.encodeWithSelector(token.APPROVE908.selector, spender, value));
}
function SAFEINCREASEALLOWANCE592(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE850(address(this), spender).ADD25(value);
CALLOPTIONALRETURN165(token, abi.encodeWithSelector(token.APPROVE908.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE974(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE850(address(this), spender).SUB66(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN165(token, abi.encodeWithSelector(token.APPROVE908.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN165(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT585(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract HashedTimeLockContract {
using SafeERC20 for IERC20;
mapping(bytes32 => LockContract) public contracts;
// / - WITHDRAWN
// INVALID - ACTIVE |
// \ - EXPIRED - REFUNDED
uint256 public constant invalid765 = 0; // Uninitialized swap -> can go to ACTIVE //inject NONSTANDARD NAMING
uint256 public constant active785 = 1; // Active swap -> can go to WITHDRAWN or EXPIRED //inject NONSTANDARD NAMING
uint256 public constant refunded800 = 2; // Swap is refunded -> final state. //inject NONSTANDARD NAMING
uint256 public constant withdrawn73 = 3; // Swap is withdrawn -> final state. //inject NONSTANDARD NAMING
uint256 public constant expired653 = 4; // Swap is expired -> can go to REFUNDED //inject NONSTANDARD NAMING
struct LockContract {
uint256 inputAmount;
uint256 outputAmount;
uint256 expiration;
uint256 status;
bytes32 hashLock;
address tokenAddress;
address sender;
address receiver;
string outputNetwork;
string outputAddress;
}
event WITHDRAW989( //inject NONSTANDARD NAMING
bytes32 id,
bytes32 secret,
bytes32 hashLock,
address indexed tokenAddress,
address indexed sender,
address indexed receiver
);
event REFUND925( //inject NONSTANDARD NAMING
bytes32 id,
bytes32 hashLock,
address indexed tokenAddress,
address indexed sender,
address indexed receiver
);
event NEWCONTRACT591( //inject NONSTANDARD NAMING
uint256 inputAmount,
uint256 outputAmount,
uint256 expiration,
bytes32 id,
bytes32 hashLock,
address indexed tokenAddress,
address indexed sender,
address indexed receiver,
string outputNetwork,
string outputAddress
);
function NEWCONTRACT928( //inject NONSTANDARD NAMING
uint256 inputAmount,
uint256 outputAmount,
uint256 expiration,
bytes32 hashLock,
address tokenAddress,
address receiver,
string calldata outputNetwork,
string calldata outputAddress
) external {
require(expiration > block.timestamp, "INVALID_TIME");
require(inputAmount > 0, "INVALID_AMOUNT");
IERC20(tokenAddress).SAFETRANSFERFROM944(
msg.sender,
address(this),
inputAmount
);
bytes32 id = sha256(
abi.encodePacked(
msg.sender,
receiver,
inputAmount,
hashLock,
expiration,
tokenAddress
)
);
require(contracts[id].status == invalid765, "SWAP_EXISTS");
contracts[id] = LockContract(
inputAmount,
outputAmount,
expiration,
active785,
hashLock,
tokenAddress,
msg.sender,
receiver,
outputNetwork,
outputAddress
);
emit NEWCONTRACT591(
inputAmount,
outputAmount,
expiration,
id,
hashLock,
tokenAddress,
msg.sender,
receiver,
outputNetwork,
outputAddress
);
}
function WITHDRAW32(bytes32 id, bytes32 secret, address tokenAddress) //inject NONSTANDARD NAMING
external
{
LockContract storage c = contracts[id];
require(c.tokenAddress == tokenAddress, "INVALID_TOKEN");
require(c.status == active785, "SWAP_NOT_ACTIVE");
require(c.expiration > block.timestamp, "INVALID_TIME");
require(
c.hashLock == sha256(abi.encodePacked(secret)),
"INVALID_SECRET"
);
c.status = withdrawn73;
IERC20(tokenAddress).SAFETRANSFER35(c.receiver, c.inputAmount);
emit WITHDRAW989(
id,
secret,
c.hashLock,
tokenAddress,
c.sender,
c.receiver
);
}
function REFUND274(bytes32 id, address tokenAddress) external { //inject NONSTANDARD NAMING
LockContract storage c = contracts[id];
require(c.tokenAddress == tokenAddress, "INVALID_TOKEN");
require(c.status == active785, "SWAP_NOT_ACTIVE");
require(c.expiration <= block.timestamp, "INVALID_TIME");
c.status = refunded800;
IERC20(tokenAddress).SAFETRANSFER35(c.sender, c.inputAmount);
emit REFUND925(id, c.hashLock, tokenAddress, c.sender, c.receiver);
}
function GETSTATUS910(bytes32[] memory ids) //inject NONSTANDARD NAMING
public
view
returns (uint256[] memory)
{
uint256[] memory result = new uint256[](ids.length);
for (uint256 index = 0; index < ids.length; index++) {
result[index] = GETSINGLESTATUS853(ids[index]);
}
return result;
}
function GETSINGLESTATUS853(bytes32 id) public view returns (uint256 result) { //inject NONSTANDARD NAMING
LockContract memory tempContract = contracts[id];
if (
tempContract.status == active785 &&
tempContract.expiration < block.timestamp
) {
result = expired653;
} else {
result = tempContract.status;
}
}
}
|
inject NONSTANDARD NAMING
|
function CALLOPTIONALRETURN165(IERC20 token, bytes memory data) private {
| 7,293,352
|
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "erc1820/contracts/ERC1820Client.sol";
import "../../interface/ERC1820Implementer.sol";
import "../../IERC1400.sol";
import "../userExtensions/IERC1400TokensSender.sol";
import "../userExtensions/IERC1400TokensRecipient.sol";
import "./IERC1400TokensValidator.sol";
import "./IERC1400TokensChecker.sol";
interface IERC1400Extended {
// Not a real interface but added here since 'granularity' doesn't belong to IERC1400
function granularity() external view returns(uint256);
}
contract ERC1400TokensChecker is IERC1400TokensChecker, ERC1820Client, ERC1820Implementer {
using SafeMath for uint256;
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker";
string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
constructor() public {
ERC1820Implementer._setInterface(ERC1400_TOKENS_CHECKER);
}
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param payload Payload of the initial transaction.
* @param partition Name of the partition.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function canTransferByPartition(bytes calldata payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData)
external
view
returns (byte, bytes32, bytes32)
{
return _canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData);
}
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param payload Payload of the initial transaction.
* @param partition Name of the partition.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function _canTransferByPartition(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData)
internal
view
returns (byte, bytes32, bytes32)
{
if(!IERC1400(msg.sender).isOperatorForPartition(partition, operator, from))
return(hex"58", "", partition); // 0x58 invalid operator (transfer agent)
if((IERC20(msg.sender).balanceOf(from) < value) || (IERC1400(msg.sender).balanceOfByPartition(partition, from) < value))
return(hex"52", "", partition); // 0x52 insufficient balance
if(to == address(0))
return(hex"57", "", partition); // 0x57 invalid receiver
address hookImplementation;
hookImplementation = ERC1820Client.interfaceAddr(from, ERC1400_TOKENS_SENDER);
if((hookImplementation != address(0))
&& !IERC1400TokensSender(hookImplementation).canTransfer(payload, partition, operator, from, to, value, data, operatorData))
return(hex"56", "", partition); // 0x56 invalid sender
hookImplementation = ERC1820Client.interfaceAddr(to, ERC1400_TOKENS_RECIPIENT);
if((hookImplementation != address(0))
&& !IERC1400TokensRecipient(hookImplementation).canReceive(payload, partition, operator, from, to, value, data, operatorData))
return(hex"57", "", partition); // 0x57 invalid receiver
hookImplementation = ERC1820Client.interfaceAddr(msg.sender, ERC1400_TOKENS_VALIDATOR);
if((hookImplementation != address(0))
&& !IERC1400TokensValidator(hookImplementation).canValidate(msg.sender, payload, partition, operator, from, to, value, data, operatorData))
return(hex"54", "", partition); // 0x54 transfers halted (contract paused)
uint256 granularity = IERC1400Extended(msg.sender).granularity();
if(!(value.div(granularity).mul(granularity) == value))
return(hex"50", "", partition); // 0x50 transfer failure
return(hex"51", "", partition); // 0x51 transfer success
}
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
*/
// function canTransfer(bytes calldata /*payload*/, address /*operator*/, address /*from*/, address /*to*/, uint256 /*value*/, bytes calldata /*data*/, bytes calldata /*operatorData*/)
// external
// view
// returns (byte, bytes32)
// {
// if(!IERC1400(msg.sender).isOperator(operator, from))
// return(hex"58", ""); // 0x58 invalid operator (transfer agent)
// byte esc;
// bytes32[] memory defaultPartitions = IERC1400(msg.sender).getDefaultPartitions();
// if(defaultPartitions.length == 0) {
// return(hex"55", ""); // 0x55 funds locked (lockup period)
// }
// uint256 _remainingValue = value;
// uint256 _localBalance;
// for (uint i = 0; i < defaultPartitions.length; i++) {
// _localBalance = IERC1400(msg.sender).balanceOfByPartition(defaultPartitions[i], from);
// if(_remainingValue <= _localBalance) {
// (esc,,) = _canTransferByPartition(payload, defaultPartitions[i], operator, from, to, _remainingValue, data, operatorData);
// _remainingValue = 0;
// break;
// } else if (_localBalance != 0) {
// (esc,,) = _canTransferByPartition(payload, defaultPartitions[i], operator, from, to, _localBalance, data, operatorData);
// _remainingValue = _remainingValue - _localBalance;
// }
// if(esc != hex"51") {
// return(esc, "");
// }
// }
// if(_remainingValue != 0) {
// return(hex"52", ""); // 0x52 insufficient balance
// }
// return(hex"51", ""); // 0x51 transfer success
// return(hex"00", "");
// }
}
|
Not a real interface but added here since 'granularity' doesn't belong to IERC1400
|
interface IERC1400Extended {
function granularity() external view returns(uint256);
pragma solidity ^0.5.0;
}
| 13,089,729
|
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
|
Reads the int112 at `mPtr` in memory.
|
function readInt112(
MemoryPointer mPtr
) internal pure returns (int112 value) {
assembly ("memory-safe") {
value := mload(mPtr)
}
}
| 8,452,157
|
./partial_match/3/0x6aa269b701E9666Fe5314ec6deB2B907cDE1A8b2/sources/LDBToken.sol
|
Transfers are allowed only after the end of minting
|
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(wasMintingFinished(), "cant transfer before minting finishes");
return super.transferFrom(_from,_to,_value);
}
| 5,218,521
|
./full_match/1/0xe4F5D08522fc6b8a84f242220181d15e1fd16526/sources/contracts/minter-suite/Minters/MinterDAExpV4.sol
|
Auction Functions Sets auction details for project `_projectId`. _projectId Project ID to set auction details for. _auctionTimestampStart Timestamp at which to start the auction. _priceDecayHalfLifeSeconds The half life with which to decay the price (in seconds). _startPrice Price at which to start the auction, in Wei. _basePrice Resting price of the auction, in Wei. Note that it is intentionally supported here that the configured price may be explicitly set to `0`./ CHECKS EFFECTS sync local max invocations if not initially populated if local max invocations and maxHasBeenInvoked are both initial values, we know they have not been populated.
|
function setAuctionDetails(
uint256 _projectId,
uint256 _auctionTimestampStart,
uint256 _priceDecayHalfLifeSeconds,
uint256 _startPrice,
uint256 _basePrice
) external {
_onlyArtist(_projectId);
ProjectConfig storage _projectConfig = projectConfig[_projectId];
require(
_projectConfig.timestampStart == 0 ||
block.timestamp < _projectConfig.timestampStart,
"No modifications mid-auction"
);
require(
block.timestamp < _auctionTimestampStart,
"Only future auctions"
);
require(
_startPrice > _basePrice,
"Auction start price must be greater than auction end price"
);
require(
(_priceDecayHalfLifeSeconds >= minimumPriceDecayHalfLifeSeconds) &&
(_priceDecayHalfLifeSeconds <=
maximumPriceDecayHalfLifeSeconds),
"Price decay half life must fall between min and max allowable values"
);
_projectConfig.timestampStart = _auctionTimestampStart.toUint64();
_projectConfig.priceDecayHalfLifeSeconds = _priceDecayHalfLifeSeconds
.toUint64();
_projectConfig.startPrice = _startPrice;
_projectConfig.basePrice = _basePrice;
emit SetAuctionDetails(
_projectId,
_auctionTimestampStart,
_priceDecayHalfLifeSeconds,
_startPrice,
_basePrice
);
if (
_projectConfig.maxInvocations == 0 &&
_projectConfig.maxHasBeenInvoked == false
) {
setProjectMaxInvocations(_projectId);
}
}
| 9,744,555
|
contract EtherTopDog {
// fund for bailing out underdogs when they are pushed out
uint private bailoutBalance = 0;
// === Underdog Payin Distribution: ===
// percent of underdog deposit amount to go in bailout fund
uint constant private bailoutFundPercent = 70;
// percent of underdog deposit that goes to the top dog's dividend
uint constant private topDogDividend = 15;
// percent of underdog deposit sent chip away top dog's strength
uint constant private topDogDecayPercent = 10;
// percent of underdog deposiot that goes to lucky dog's dividend
uint constant private luckyDogDividend = 3;
// vision dog takes a small fee from each underdog deposit
uint constant private visionDogFeePercent = 2;
// === === === === === === === === ===
// percentage markup from payin for calculating new mininum TopDog price threshold
uint constant private topDogMinMarkup = 125;
// minimum required deposit to become the next Top Dog
// (aka Top Dog strength / lowest possible takeover threshold)
// starts at 125% of Top Dog's deposit, slowly declines as underdogs join
uint private topDogMinPrice = 1;
// range above the topdog strength (aka topDogMinPrice) within which
// the randomly generated required takeover threhold is set
uint constant private topDogBuyoutRange = 150;
// percentage of topdog buyout fee gets paid to creator
uint constant private visionDogBuyPercent = 5;
// underdog payout markup, as a percentage of their deposits
// gets reset to 150% after each round when the top dog gets replaced
// gradually decays to mininum of 120% as underdogs chip away at top dog's strength
uint private underDogMarkup = 150;
// as top dog price declines, these keep track of the range
// so underDopMarkup can slowly go from 150% to 120% return
// as the Top Dog mininum price starts at the price ceiling,
// and declines until it reaches the floor (or lower)
uint private topDogPriceCeiling = 0;
uint private topDogPriceFloor = 0;
// total collected fees from underdogs, paid out whenever Top Dog is bought out
uint private visionFees = 0;
// current top dog
address private topDog = 0x0;
// underdog entries
struct Underdog {
address addr;
uint deposit;
uint payout;
uint bailouts;
}
Underdog[] private Underdogs;
// player names for fun
mapping (address => string) dogNames;
// current lucky dog (if exists) will receive 3% of underdog payins
// specified as index in Underdogs array
// 0 = nobody (the very first underdog to join the game is precluded from becoming the Lucky Dog)
uint private luckyDog = 0;
// index of next underdog to be paid
uint private payoutIndex = 0;
// count payouts made by underdogs currently in the game
// so we can have a baseline for dividing the scraps
uint private payoutCount = 0;
// address of the creator
address private visionDog;
function EtherTopDog() {
visionDog = msg.sender;
}
// ==== Game Info Display ABI functions: ====
function underdogPayoutFund() public constant returns (uint balance) {
balance = bailoutBalance;
}
function nextUnderdogPayout() public constant returns (uint) {
if (Underdogs.length - payoutIndex >= 1) {
return Underdogs[payoutIndex].payout;
}
}
function underdogPayoutMarkup() public constant returns (uint) {
return underDogMarkup;
}
function topDogInfo() public constant returns (string name, uint strength) {
if (topDog != address(0x0)) {
name = getDogName(topDog);
} else {
name = "[not set]";
}
strength = topDogMinPrice;
}
function luckyDogInfo() public constant returns (string name) {
if (luckyDog > 0) {
name = getDogName(Underdogs[luckyDog].addr);
} else {
name = "[nobody]";
}
}
function underdogCount() constant returns (uint) {
return Underdogs.length - payoutIndex;
}
function underdogInfo(uint linePosition) constant returns (string name, address dogAddress, uint deposit, uint payout, uint scrapBonus) {
if (linePosition > 0 && linePosition <= Underdogs.length - payoutIndex) {
Underdog thedog = Underdogs[payoutIndex + (linePosition - 1)];
name = getDogName(thedog.addr);
dogAddress = thedog.addr;
deposit = thedog.deposit;
payout= thedog.payout;
scrapBonus = thedog.bailouts;
}
}
// ==== End ABI Functions ====
// ==== Public transaction functions: ====
// default fallback : play a round
function() {
dogFight();
}
// sets name, optionally plays a round if Ether was sent
function setName(string DogName) {
if (bytes(DogName).length >= 2 && bytes(DogName).length <= 16)
dogNames[msg.sender] = DogName;
// if a deposit was sent, play it!
if (msg.value > 0) {
dogFight();
}
}
function dogFight() public {
// minimum 1 ETH required to play
if (msg.value < 1 ether) {
msg.sender.send(msg.value);
return;
}
// does a topdog exist ?
if (topDog != address(0x0)) {
// the actual amount required to knock out the top dig is random within the buyout range
uint topDogPrice = topDogMinPrice + randInt( (topDogMinPrice * topDogBuyoutRange / 100) - topDogMinPrice, 4321);
// Calculate the top dog price
if (msg.value >= topDogPrice) {
// They bought out the top dog!
buyTopDog(topDogPrice, msg.value - topDogPrice);
} else {
// didn't buy the top dog, this participant becomes an underdog!
addUnderDog(msg.value);
}
} else {
// no top dog exists yet, the game must be just getting started
// put the first deposit in the bailout fund, initialize the game
// set first topDog
topDog = msg.sender;
topDogPriceFloor = topDogMinPrice;
bailoutBalance += msg.value;
topDogMinPrice = msg.value * topDogMinMarkup / 100;
topDogPriceCeiling = topDogMinPrice;
}
}
// ==== End Public Functions ====
// ==== Private Functions: ====
function addUnderDog(uint buyin) private {
uint bailcount = 0;
// amount this depositor will be paid when the fund allows
uint payoutval = buyin * underDogMarkup / 100;
// add portion of deposit to bailout fund
bailoutBalance += buyin * bailoutFundPercent / 100;
// top dog / lucky dog dividends
uint topdividend = buyin * topDogDividend / 100;
uint luckydividend = buyin * luckyDogDividend / 100;
// is there a lucky dog?
if (luckyDog != 0 && luckyDog >= payoutIndex) {
// pay lucky dog dividends
Underdogs[luckyDog].addr.send(luckydividend);
} else {
// no lucky dog exists, all dividends go to top dog
topdividend += luckydividend;
}
// pay top dog dividends
topDog.send(topdividend);
// chip away at the top dog's strength
uint topdecay = (buyin * topDogDecayPercent / 100);
topDogMinPrice -= topdecay;
// update underdog markup % for next round
// specified as n/100000 to avoid floating point math
uint decayfactor = 0;
// calculate the payout markup for next underdog
if (topDogMinPrice > topDogPriceFloor) {
uint decayrange = (topDogPriceCeiling - topDogPriceFloor);
decayfactor = 100000 * (topDogPriceCeiling - topDogMinPrice) / decayrange;
} else {
decayfactor = 100000;
}
// markup will be between 120-150% corresponding to current top dog price decline (150% - 30% = 120%)
underDogMarkup = 150 - (decayfactor * 30 / 100000);
// creator takes a slice
visionFees += (buyin * visionDogFeePercent / 100);
// payout as many previous underdogs as the fund can afford
while (payoutIndex < Underdogs.length && bailoutBalance >= Underdogs[payoutIndex].payout ) {
payoutCount -= Underdogs[payoutIndex].bailouts;
bailoutBalance -= Underdogs[payoutIndex].payout;
Underdogs[payoutIndex].addr.send(Underdogs[payoutIndex].payout);
// if the lucky dog was bailed out, the user who did it now becomes the lucky dog
if (payoutIndex == luckyDog && luckyDog != 0)
luckyDog = Underdogs.length;
payoutIndex++;
bailcount++;
payoutCount++;
}
// add the new underdog to the queue
Underdogs.push(Underdog(msg.sender, buyin, payoutval, bailcount));
}
function buyTopDog(uint buyprice, uint surplus) private {
// take out vizionDog fee
uint vfee = buyprice * visionDogBuyPercent / 100;
uint dogpayoff = (buyprice - vfee);
// payout previous top dog
topDog.send(dogpayoff);
visionFees += vfee;
// send buy fee (plus previous collected underdog fees) to visionDog
visionDog.send(visionFees);
visionFees = 0;
// record a price floor for underdog markup decay calculation during the next round:
// the mininum purchase price before buyout
topDogPriceFloor = topDogMinPrice;
// set the initial minimum buy price for the next top dog
topDogMinPrice = msg.value * topDogMinMarkup / 100;
// the price ceiling for calculating the underdog markup decay is the new minimum price
topDogPriceCeiling = topDogMinPrice;
// check for eligible lucky dog...
// if (Underdogs.length - payoutIndex > 0) {
// lucky dog is most recent underdog to make an entry
// luckyDog = Underdogs.length - 1;
// } else {
// no dogs waiting in line? all dividends will go to top dog this round
// luckyDog = 0;
// }
// reset underdog markup for next round
underDogMarkup = 150;
// how many dogs are waiting?
uint linelength = Underdogs.length - payoutIndex;
// surplus goes to pay scraps to random underdogs
// calculate and pay scraps
// are there underdogs around to receive the scraps?
if (surplus > 0 && linelength > 0 ) {
throwScraps(surplus);
}
// if there are any underdogs in line, the lucky dog will be picked from among them
if (linelength > 0) {
// randomly pick a new lucky dog, with luck weighted toward more recent entries
// weighting works like this:
// For example, if the line length is 6, the most recent entry will
// be 6 times more likely than the oldest (6/21 odds),
// the second most recent will be 5 times more likely than the oldest (5/21 odds)
// the third most recent will be 4 times as likely as the oldest (4/21 odds),
// etc...
// of course, the player that has been in line longest is
// least likely to be lucky (1/21 odds in this example)
// and will be getting sent out of the game soonest anyway
uint luckypickline = (linelength % 2 == 1) ?
( linelength / 2 + 1 ) + (linelength + 1) * (linelength / 2) : // odd
( (linelength + 1) * (linelength / 2) ); // even
uint luckypick = randInt(luckypickline, 69);
uint pickpos = luckypickline - linelength;
uint linepos = 1;
while (pickpos >= luckypick && linepos < linelength) {
pickpos -= (linelength - linepos);
linepos++;
}
luckyDog = Underdogs.length - linepos;
} else {
// no underdogs in line? no lucky dog this round.
// (should only possibly happen when game starts)
luckyDog = 0;
}
// the new top dog is crowned!
topDog = msg.sender;
}
function throwScraps(uint totalscrapvalue) private {
// how many dogs are waiting?
uint linelength = Underdogs.length - payoutIndex;
// to keep from having too many transactions, make sure we never have more than 7 scraps.
// the more dogs in line, the more we jump over when scraps get scattered
uint skipstep = (linelength / 7) + 1;
// how many pieces to divide (roughly, randomization might make it more or less)
uint pieces = linelength / skipstep;
// how far from the end of the queue to start throwing the first scrap (semi-random)
uint startoffset = randInt(skipstep, 42) - 1;
// base size for scraps...
uint scrapbasesize = totalscrapvalue / (pieces + payoutCount);
// minimum base scrap size of 0.5 eth
if (scrapbasesize < 500 finney) {
scrapbasesize = 500 finney;
}
uint scrapsize;
uint sptr = Underdogs.length - 1 - startoffset;
uint scrapvalueleft = totalscrapvalue;
while (pieces > 0 && scrapvalueleft > 0 && sptr >= payoutIndex) {
// those who bailed out other dogs get bigger scraps
// size of the scrap is multiplied by # of other dogs the user bailed out
scrapsize = scrapbasesize * (Underdogs[sptr].bailouts + 1);
// scraps can never be more than what's in the pile
if (scrapsize < scrapvalueleft) {
scrapvalueleft -= scrapsize;
} else {
scrapsize = scrapvalueleft;
scrapvalueleft = 0;
}
// pay it
Underdogs[sptr].addr.send(scrapsize);
pieces--;
sptr -= skipstep;
}
// any scraps left uncaught? put them in the bailout fund for the underdogs
if (scrapvalueleft > 0) {
bailoutBalance += scrapvalueleft;
}
}
function getDogName(address adr) private constant returns (string thename) {
if (bytes(dogNames[adr]).length > 0)
thename = dogNames[adr];
else
thename = 'Unnamed Mutt';
}
// Generate pseudo semi-random number between 1 - max
function randInt(uint max, uint seedswitch) private constant returns (uint randomNumber) {
return( uint(sha3(block.blockhash(block.number-1), block.timestamp + seedswitch) ) % max + 1 );
}
}
|
take out vizionDog fee payout previous top dog send buy fee (plus previous collected underdog fees) to visionDog record a price floor for underdog markup decay calculation during the next round: the mininum purchase price before buyout set the initial minimum buy price for the next top dog the price ceiling for calculating the underdog markup decay is the new minimum price check for eligible lucky dog... if (Underdogs.length - payoutIndex > 0) { lucky dog is most recent underdog to make an entry luckyDog = Underdogs.length - 1; } else { no dogs waiting in line? all dividends will go to top dog this round luckyDog = 0; } reset underdog markup for next round how many dogs are waiting? surplus goes to pay scraps to random underdogs calculate and pay scraps are there underdogs around to receive the scraps? if there are any underdogs in line, the lucky dog will be picked from among them randomly pick a new lucky dog, with luck weighted toward more recent entries weighting works like this: For example, if the line length is 6, the most recent entry will be 6 times more likely than the oldest (6/21 odds), the second most recent will be 5 times more likely than the oldest (5/21 odds) the third most recent will be 4 times as likely as the oldest (4/21 odds), etc... of course, the player that has been in line longest is least likely to be lucky (1/21 odds in this example) and will be getting sent out of the game soonest anyway
|
function buyTopDog(uint buyprice, uint surplus) private {
uint vfee = buyprice * visionDogBuyPercent / 100;
uint dogpayoff = (buyprice - vfee);
topDog.send(dogpayoff);
visionFees += vfee;
visionDog.send(visionFees);
visionFees = 0;
topDogPriceFloor = topDogMinPrice;
topDogMinPrice = msg.value * topDogMinMarkup / 100;
topDogPriceCeiling = topDogMinPrice;
underDogMarkup = 150;
uint linelength = Underdogs.length - payoutIndex;
if (surplus > 0 && linelength > 0 ) {
throwScraps(surplus);
}
if (linelength > 0) {
uint luckypickline = (linelength % 2 == 1) ?
uint luckypick = randInt(luckypickline, 69);
uint pickpos = luckypickline - linelength;
uint linepos = 1;
while (pickpos >= luckypick && linepos < linelength) {
pickpos -= (linelength - linepos);
linepos++;
}
luckyDog = Underdogs.length - linepos;
}
}
| 15,787,469
|
./full_match/41/0x4c0E2d50A0B65c59E0a1d22067d0821761D1aE7e/sources/contracts/IceCreamZombies.sol
|
use vesting from snapshotV1
|
function importNftsFromV1(NftInfo[] calldata snapshotV1) external onlyOwner() {
uint256 totalAmountToStake;
for (uint256 i = 0; i < snapshotV1.length; i++) {
NftInfo calldata nft = snapshotV1[i];
if (nft.amountStaked > 0) {
uint256 newAmountStaked = nft.amountStaked / CONVERSION_RATE;
totalAmountToStake += newAmountStaked;
_mintV1TokenId(nft.owner, nft.tokenId);
tokenStatus[nft.tokenId] = StakeInfo({
amountStaked: newAmountStaked,
vestingStart: nft.vestingStart,
vestingEnd: nft.vestingEnd
});
_updateStakeRequiredEveryTenMints();
}
}
STAKE_TOKEN.transferFrom(msg.sender, address(this), totalAmountToStake);
}
| 16,378,009
|
./partial_match/56/0xD02DDb9d82467EaF3FE853448CdD20950366a89B/sources/MasterChef.sol
|
Safe tap transfer function, just in case if rounding error causes pool to not have enough TAPs.
|
function safeTapTransfer(address _to, uint256 _amount) internal {
uint256 tapBal = tap.balanceOf(address(this));
if (_amount > tapBal) {
tap.transfer(_to, tapBal);
tap.transfer(_to, _amount);
}
}
| 11,132,980
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018-2020 Crossbar.io Technologies GmbH and contributors.
//
// 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.5.12;
pragma experimental ABIEncoderV2;
// https://openzeppelin.org/api/docs/math_SafeMath.html
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./XBRMaintained.sol";
import "./XBRTypes.sol";
import "./XBRToken.sol";
import "./XBRNetwork.sol";
import "./XBRCatalog.sol";
/**
* The `XBR Market <https://github.com/crossbario/xbr-protocol/blob/master/contracts/XBRMarket.sol>`__
* contract manages XBR data markets and serves as an anchor for all payment and paying channels for
* each respective market.
*/
contract XBRMarket is XBRMaintained {
// Add safe math functions to uint256 using SafeMath lib from OpenZeppelin
using SafeMath for uint256;
/// Event emitted when a new market was created.
event MarketCreated (bytes16 indexed marketId, uint created, uint32 marketSeq, address owner, address coin, string terms,
string meta, address maker, uint256 providerSecurity, uint256 consumerSecurity, uint256 marketFee);
/// Event emitted when a market was updated.
event MarketUpdated (bytes16 indexed marketId, uint32 marketSeq, address owner, address coin, string terms, string meta,
address maker, uint256 providerSecurity, uint256 consumerSecurity, uint256 marketFee);
/// Event emitted when a market was closed.
event MarketClosed (bytes16 indexed marketId);
/// Event emitted when a new actor joined a market.
event ActorJoined (bytes16 indexed marketId, address actor, uint8 actorType, uint joined,
uint256 security, string meta);
/// Event emitted when an actor has left a market.
event ActorLeft (bytes16 indexed marketId, address actor, uint8 actorType);
/// Event emitted when an actor has set consent on a ``(market, delegate, api)`` triple.
event ConsentSet (address member, uint256 updated, bytes16 marketId, address delegate,
uint8 delegateType, bytes16 apiCatalog, bool consent, string servicePrefix);
/// Instance of XBRNetwork contract this contract is linked to.
XBRNetwork public network;
/// Instance of XBRCatalog contract this contract is linked to.
XBRCatalog public catalog;
/// Created markets are sequence numbered using this counter (to allow deterministic collision-free IDs for markets)
uint32 private marketSeq = 1;
/// Current XBR Markets ("market directory")
mapping(bytes16 => XBRTypes.Market) public markets;
/// List of IDs of current XBR Markets.
bytes16[] public marketIds;
/// Index: maker address => market ID
mapping(address => bytes16) public marketsByMaker;
/// Index: market owner address => [market ID]
mapping(address => bytes16[]) public marketsByOwner;
// Constructor for this contract, only called once (when deploying the network).
//
// @param networkAdr The XBR network contract this instance is associated with.
constructor (address networkAdr, address catalogAdr) public {
network = XBRNetwork(networkAdr);
catalog = XBRCatalog(catalogAdr);
}
/// Create a new XBR market. The sender of the transaction must be XBR network member
/// and automatically becomes owner of the new market.
///
/// @param marketId The ID of the market to create. Must be unique (not yet existing).
/// @param coin The ERC20 coin to be used as the means of payment in the market.
/// @param terms Multihash for market terms set by the market owner.
/// @param meta Multihash for optional market metadata.
/// @param maker The address of the XBR market maker that will run this market. The delegate of the market owner.
/// @param providerSecurity The amount of coins a XBR provider joining the market must deposit.
/// @param consumerSecurity The amount of coins a XBR consumer joining the market must deposit.
/// @param marketFee The fee taken by the market (beneficiary is the market owner). The fee is a percentage of
/// the revenue of the XBR Provider that receives coins paid for transactions.
/// The fee must be between 0% (inclusive) and 100% (inclusive), and is expressed as
/// a fraction of the total supply of coins in the ERC20 token specified for the market.
function createMarket (bytes16 marketId, address coin, string memory terms, string memory meta, address maker,
uint256 providerSecurity, uint256 consumerSecurity, uint256 marketFee) public {
_createMarket(msg.sender, block.number, marketId, coin, terms, meta, maker,
providerSecurity, consumerSecurity, marketFee, "");
}
/// Create a new XBR market for a member. The member must be XBR network member, must have signed the
/// transaction data, and will become owner of the new market.
///
/// Note: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member The member that creates the market (will become market owner).
/// @param created Block number when the market was created.
/// @param marketId The ID of the market to create. Must be unique (not yet existing).
/// @param coin The ERC20 coin to be used as the means of payment in the market.
/// @param terms Multihash for market terms set by the market owner.
/// @param meta Multihash for optional market metadata.
/// @param maker The address of the XBR market maker that will run this market. The delegate of the market owner.
/// @param providerSecurity The amount of coins a XBR provider joining the market must deposit.
/// @param consumerSecurity The amount of coins a XBR consumer joining the market must deposit.
/// @param marketFee The fee taken by the market (beneficiary is the market owner). The fee is a percentage of
/// the revenue of the XBR Provider that receives coins paid for transactions.
/// The fee must be between 0% (inclusive) and 100% (inclusive), and is expressed as
/// a fraction of the total supply of coins in the ERC20 token specified for the market.
/// @param signature EIP712 signature created by the member.
function createMarketFor (address member, uint256 created, bytes16 marketId, address coin,
string memory terms, string memory meta, address maker, uint256 providerSecurity, uint256 consumerSecurity,
uint256 marketFee, bytes memory signature) public {
/*
require(XBRTypes.verify(member, XBRTypes.EIP712MarketCreate(network.verifyingChain(), network.verifyingContract(),
member, created, marketId, coin, terms, meta, maker, providerSecurity, consumerSecurity, marketFee), signature),
"INVALID_MARKET_CREATE_SIGNATURE");
*/
require(XBRTypes.verify(member, XBRTypes.EIP712MarketCreate(network.verifyingChain(), network.verifyingContract(),
member, created, marketId, coin, terms, meta, maker, marketFee), signature),
"INVALID_MARKET_CREATE_SIGNATURE");
// signature must have been created in a window of 5 blocks from the current one
require(created <= block.number && created >= (block.number - 4), "INVALID_CREATED_BLOCK_NUMBER");
_createMarket(member, created, marketId, coin, terms, meta, maker,
providerSecurity, consumerSecurity, marketFee, signature);
}
function _createMarket (address member, uint256 created, bytes16 marketId, address coin, string memory terms,
string memory meta, address maker, uint256 providerSecurity, uint256 consumerSecurity, uint256 marketFee,
bytes memory signature) private {
(, , , XBRTypes.MemberLevel member_level, ) = network.members(member);
// the market operator (owner) must be a registered member
require(member_level == XBRTypes.MemberLevel.ACTIVE ||
member_level == XBRTypes.MemberLevel.VERIFIED, "SENDER_NOT_A_MEMBER");
// market must not yet exist (to generate a new marketId: )
require(markets[marketId].owner == address(0), "MARKET_ALREADY_EXISTS");
// FIXME: expand this to check against XBRNetwork.coins (which is not yet there)
// require(coin == address(network.token()), "INVALID_COIN");
require(network.coins(coin) == true, "INVALID_COIN");
// must provide a valid market maker address already when creating a market
require(maker != address(0), "INVALID_MAKER");
// the market maker can only work for one market
require(marketsByMaker[maker] == bytes16(0), "MAKER_ALREADY_WORKING_FOR_OTHER_MARKET");
// provider security must be non-negative (and obviously smaller than the total token supply)
require(providerSecurity >= 0 && providerSecurity <= network.token().totalSupply(), "INVALID_PROVIDER_SECURITY");
// consumer security must be non-negative (and obviously smaller than the total token supply)
require(consumerSecurity >= 0 && consumerSecurity <= network.token().totalSupply(), "INVALID_CONSUMER_SECURITY");
// FIXME: treat market fee
require(marketFee >= 0 && marketFee < (network.token().totalSupply() - 10**7) * 10**18, "INVALID_MARKET_FEE");
// now remember out new market ..
markets[marketId] = XBRTypes.Market(created, marketSeq, member, coin, terms, meta, maker,
providerSecurity, consumerSecurity, marketFee, signature, new address[](0), new address[](0));
// .. and the market-maker-to-market mapping
marketsByMaker[maker] = marketId;
// .. and the market-owner-to-market mapping
marketsByOwner[member].push(marketId);
// .. and list of markst IDs
marketIds.push(marketId);
// increment market sequence for next market
marketSeq = marketSeq + 1;
// notify observers (eg a dormant market maker waiting to be associated)
emit MarketCreated(marketId, created, marketSeq, member, coin, terms, meta, maker,
providerSecurity, consumerSecurity, marketFee);
}
/// Join the given XBR market as the specified type of actor, which must be PROVIDER or CONSUMER.
///
/// @param marketId The ID of the XBR data market to join.
/// @param actorType The type of actor under which to join: PROVIDER or CONSUMER.
/// @param meta The XBR market provider/consumer metadata. IPFS Multihash pointing to a JSON file with metadata.
function joinMarket (bytes16 marketId, uint8 actorType, string memory meta) public returns (uint256) {
return _joinMarket(msg.sender, block.number, marketId, actorType, meta, "");
}
/// Join the specified member to the given XBR market as the specified type of actor,
/// which must be PROVIDER or CONSUMER.
///
/// Note: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member The member that creates the market (will become market owner).
/// @param joined Block number when the member joined the market.
/// @param marketId The ID of the XBR data market to join.
/// @param actorType The type of actor under which to join: PROVIDER or CONSUMER.
/// @param meta The XBR market provider/consumer metadata. IPFS Multihash pointing to a JSON file with metadata.
/// @param signature EIP712 signature created by the member.
function joinMarketFor (address member, uint256 joined, bytes16 marketId, uint8 actorType,
string memory meta, bytes memory signature) public returns (uint256) {
require(XBRTypes.verify(member, XBRTypes.EIP712MarketJoin(network.verifyingChain(), network.verifyingContract(),
member, joined, marketId, actorType, meta), signature), "INVALID_MARKET_JOIN_SIGNATURE");
// signature must have been created in a window of 5 blocks from the current one
require(joined <= block.number && joined >= (block.number - 4), "INVALID_REGISTERED_BLOCK_NUMBER");
return _joinMarket(member, joined, marketId, actorType, meta, signature);
}
function _joinMarket (address member, uint256 joined, bytes16 marketId, uint8 actorType,
string memory meta, bytes memory signature) private returns (uint256) {
(, , , XBRTypes.MemberLevel member_level, ) = network.members(member);
// the joining sender must be a registered member
require(member_level == XBRTypes.MemberLevel.ACTIVE, "SENDER_NOT_A_MEMBER");
// the market to join must exist
require(markets[marketId].owner != address(0), "NO_SUCH_MARKET");
// the market owner cannot join as an actor (provider/consumer) in the market
require(markets[marketId].owner != member, "SENDER_IS_OWNER");
// the joining member must join as a data provider (seller) or data consumer (buyer)
require(actorType == uint8(XBRTypes.ActorType.PROVIDER) ||
actorType == uint8(XBRTypes.ActorType.CONSUMER) ||
actorType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER), "INVALID_ACTOR_TYPE");
// get the security amount required for joining the market (if any)
uint256 security = 0;
if (actorType == uint8(XBRTypes.ActorType.PROVIDER) || actorType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
// the joining member must not be joined as a provider already
require(uint8(markets[marketId].providerActors[member].joined) == 0, "ALREADY_JOINED_AS_PROVIDER");
security += markets[marketId].providerSecurity;
}
if (actorType == uint8(XBRTypes.ActorType.CONSUMER) || actorType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
// the joining member must not be joined as a consumer already
require(uint8(markets[marketId].consumerActors[member].joined) == 0, "ALREADY_JOINED_AS_CONSUMER");
security += markets[marketId].consumerSecurity;
}
if (security > 0) {
// Transfer (if any) security to the market owner (for ActorType.CONSUMER or ActorType.PROVIDER)
bool success = network.token().transferFrom(member, markets[marketId].owner, security);
require(success, "JOIN_MARKET_TRANSFER_FROM_FAILED");
}
// remember actor (by actor address) within market
if (actorType == uint8(XBRTypes.ActorType.PROVIDER) || actorType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
markets[marketId].providerActors[member] = XBRTypes.Actor(joined, markets[marketId].providerSecurity, meta, signature, new address[](0));
markets[marketId].providerActorAdrs.push(member);
}
if (actorType == uint8(XBRTypes.ActorType.CONSUMER) || actorType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
markets[marketId].consumerActors[member] = XBRTypes.Actor(joined, markets[marketId].consumerSecurity, meta, signature, new address[](0));
markets[marketId].consumerActorAdrs.push(member);
}
// emit event ActorJoined(bytes16 marketId, address actor, ActorType actorType, uint joined,
// uint256 security, string meta)
emit ActorJoined(marketId, member, actorType, joined, security, meta);
// return effective security transferred
return security;
}
/// Track consent of an actor in a market to allow the specified seller or buyer delegate
/// to provide or consume data under the respective API catalog in the given market.
///
/// @param marketId The ID of the XBR data market in which to provide or consume data. Any
/// terms attached to the market or the API apply.
/// @param delegate The address of the off-chain provider or consumer delegate, which is a piece
/// of software acting on behalf and under consent of the actor in the market.
/// @param delegateType The type of off-chain delegate, a data provider or data consumer.
/// @param apiCatalog The ID of the API or API catalog to which the consent shall apply.
/// @param consent Consent granted or revoked.
/// @param servicePrefix The WAMP URI prefix to be used by the delegate in the data plane realm.
function setConsent (bytes16 marketId, address delegate, uint8 delegateType, bytes16 apiCatalog,
bool consent, string memory servicePrefix) public {
return _setConsent(msg.sender, block.number, marketId, delegate, delegateType,
apiCatalog, consent, servicePrefix, "");
}
/// Track consent of an actor in a market to allow the specified seller or buyer delegate
/// to provide or consume data under the respective API catalog in the given market.
///
/// IMPORTANT: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member Address of member (which must be actor in the market) that sets consent.
/// @param updated Block number at which the consent setting member has created the signature.
/// @param marketId The ID of the XBR data market in which to provide or consume data. Any
/// terms attached to the market or the API apply.
/// @param delegate The address of the off-chain provider or consumer delegate, which is a piece
/// of software acting on behalf and under consent of the actor in the market.
/// @param delegateType The type of off-chain delegate, a data provider or data consumer.
/// @param apiCatalog The ID of the API or API catalog to which the consent shall apply.
/// @param consent Consent granted or revoked.
/// @param servicePrefix The WAMP URI prefix to be used by the delegate in the data plane realm.
/// @param signature EIP712 signature, signed by the consent setting member.
function setConsentFor (address member, uint256 updated, bytes16 marketId, address delegate,
uint8 delegateType, bytes16 apiCatalog, bool consent, string memory servicePrefix,
bytes memory signature) public {
require(XBRTypes.verify(member, XBRTypes.EIP712Consent(network.verifyingChain(), network.verifyingContract(),
member, updated, marketId, delegate, delegateType, apiCatalog, consent, servicePrefix), signature),
"INVALID_CONSENT_SIGNATURE");
// signature must have been created in a window of 5 blocks from the current one
require(updated <= block.number && updated >= (block.number - 4), "INVALID_CONSENT_BLOCK_NUMBER");
return _setConsent(member, updated, marketId, delegate, delegateType,
apiCatalog, consent, servicePrefix, signature);
}
function _setConsent (address member, uint256 updated, bytes16 marketId, address delegate,
uint8 delegateType, bytes16 apiCatalog, bool consent, string memory servicePrefix,
bytes memory signature) public {
(, , , XBRTypes.MemberLevel member_level, ) = network.members(member);
// the joining sender must be a registered member
require(member_level == XBRTypes.MemberLevel.ACTIVE, "SENDER_NOT_A_MEMBER");
// the market must exist
require(markets[marketId].owner != address(0), "NO_SUCH_MARKET");
// consent to the delegate acting as a data provider (seller) or data consumer (buyer)
require(delegateType == uint8(XBRTypes.ActorType.PROVIDER) ||
delegateType == uint8(XBRTypes.ActorType.CONSUMER) ||
delegateType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER), "INVALID_ACTOR_TYPE");
if (delegateType == uint8(XBRTypes.ActorType.PROVIDER) || delegateType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
// the member must be a provider actor in the market
require(uint8(markets[marketId].providerActors[member].joined) != 0, "MEMBER_NOT_PROVIDER");
}
if (delegateType == uint8(XBRTypes.ActorType.CONSUMER) || delegateType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
// the member must be a consumer actor in the market
require(uint8(markets[marketId].consumerActors[member].joined) != 0, "MEMBER_NOT_CONSUMER");
}
// must provide a valid delegate address, but the delegate doesn't need to be member!
require(delegate != address(0), "INVALID_CHANNEL_DELEGATE");
// the catalog must exist
(uint256 catalogCreated, , , , , ) = catalog.catalogs(apiCatalog);
require(catalogCreated != 0, "NO_SUCH_CATALOG");
// must have a service prefix set
require(keccak256(abi.encode(servicePrefix)) != keccak256(abi.encode("")), "SERVICE_PREFIX_EMPTY");
// store consent status as provider delegate
if (delegateType == uint8(XBRTypes.ActorType.PROVIDER) || delegateType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
markets[marketId].providerActors[member].delegates[delegate][apiCatalog] = XBRTypes.Consent(
updated, consent, servicePrefix, signature);
}
// store consent status as consumer delegate
if (delegateType == uint8(XBRTypes.ActorType.CONSUMER) || delegateType == uint8(XBRTypes.ActorType.PROVIDER_CONSUMER)) {
markets[marketId].consumerActors[member].delegates[delegate][apiCatalog] = XBRTypes.Consent(
updated, consent, servicePrefix, signature);
}
// notify observers of changed consent status
emit ConsentSet(member, updated, marketId, delegate, delegateType, apiCatalog, consent, servicePrefix);
}
/// Get the total number of markets defined.
function countMarkets() public view returns (uint) {
return marketIds.length;
}
/*
// TypeError: Only libraries are allowed to use the mapping type in public or external functions.
function getMarket(bytes16 marketId) public view returns (XBRTypes.Market memory) {
return markets[marketId];
}
*/
/// Get the market owner for the given market.
function getMarketOwner(bytes16 marketId) public view returns (address) {
return markets[marketId].owner;
}
/// Get the market maker for the given market.
function getMarketMaker(bytes16 marketId) public view returns (address) {
return markets[marketId].maker;
}
/// Get the n-th market owned by the given member.
function getMarketsByOwner(address owner, uint index) public view returns (bytes16) {
return marketsByOwner[owner][index];
}
/// Check if the specified member is actor in the given market.
function isActor(bytes16 marketId, address actor, XBRTypes.ActorType actorType) public view returns (bool) {
if (markets[marketId].owner == address(0)) {
return false;
} else {
if (actorType == XBRTypes.ActorType.CONSUMER) {
return markets[marketId].consumerActors[actor].joined > 0;
} else if (actorType == XBRTypes.ActorType.PROVIDER) {
return markets[marketId].providerActors[actor].joined > 0;
} else {
return false;
}
}
}
/// Get the number of market owned by the specified member.
function countMarketsByOwner(address owner) public view returns (uint) {
return marketsByOwner[owner].length;
}
/// Get market actor data for the given actor (address) and actor type in the specified market.
function getMarketActor (bytes16 marketId, address actor, uint8 actorType) public view
returns (uint, uint256, string memory, bytes memory)
{
// the market must exist
require(markets[marketId].owner != address(0), "NO_SUCH_MARKET");
// must ask for a data provider (seller) or data consumer (buyer)
require(actorType == uint8(XBRTypes.ActorType.PROVIDER) ||
actorType == uint8(XBRTypes.ActorType.CONSUMER), "INVALID_ACTOR_TYPE");
if (actorType == uint8(XBRTypes.ActorType.CONSUMER)) {
XBRTypes.Actor storage _actor = markets[marketId].consumerActors[actor];
return (_actor.joined, _actor.security, _actor.meta, _actor.signature);
} else {
XBRTypes.Actor storage _actor = markets[marketId].providerActors[actor];
return (_actor.joined, _actor.security, _actor.meta, _actor.signature);
}
}
/**
* Lookup all provider actors in a XBR Market.
*
* @param marketId The XBR Market to provider actors for.
* @return List of provider actor addresses in the market.
*/
function getAllMarketProviders(bytes16 marketId) public view returns (address[] memory) {
return markets[marketId].providerActorAdrs;
}
/**
* Lookup all consumer actors in a XBR Market.
*
* @param marketId The XBR Market to consumer actors for.
* @return List of consumer actor addresses in the market.
*/
function getAllMarketConsumers(bytes16 marketId) public view returns (address[] memory) {
return markets[marketId].consumerActorAdrs;
}
/**
* Lookup all payment channels for an consumer actor in a XBR Market.
*
* @param marketId The XBR Market to get payment channels for.
* @param actor The XBR actor to get payment channels for.
* @return List of contract addresses of payment channels in the market.
*/
function getAllPaymentChannels(bytes16 marketId, address actor) public view returns (address[] memory) {
return markets[marketId].consumerActors[actor].channels;
}
/**
* Lookup all paying channels for an provider actor in a XBR Market.
*
* @param marketId The XBR Market to get paying channels for.
* @param actor The XBR actor to get paying channels for.
* @return List of contract addresses of paying channels in the market.
*/
function getAllPayingChannels(bytes16 marketId, address actor) public view returns (address[] memory) {
return markets[marketId].providerActors[actor].channels;
}
/**
* Lookup the current payment channel to use for the given delegate in the given market.
*
* @param marketId The XBR Market to get the current payment channel address for.
* @param delegate The delegate to get the current payment channel address for.
* @return Current payment channel address for the given delegate/market.
*/
function currentPaymentChannelByDelegate(bytes16 marketId, address delegate) public view returns (address) {
return markets[marketId].currentPaymentChannelByDelegate[delegate];
}
/**
* Lookup the current paying channel to use for the given delegate in the given market.
*
* @param marketId The XBR Market to get the current paying channel address for.
* @param delegate The delegate to get the current paying channel address for.
* @return Current paying channel address for the given delegate/market.
*/
function currentPayingChannelByDelegate(bytes16 marketId, address delegate) public view returns (address) {
return markets[marketId].currentPayingChannelByDelegate[delegate];
}
}
|
Get the n-th market owned by the given member.
|
function getMarketsByOwner(address owner, uint index) public view returns (bytes16) {
return marketsByOwner[owner][index];
}
| 2,572,577
|
pragma solidity ^0.4.18;
/// @title Ownable contract
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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title Mortal contract - used to selfdestruct once we have no use of this contract
contract Mortal is Ownable {
function executeSelfdestruct() onlyOwner {
selfdestruct(owner);
}
}
/// @title ERC20 contract
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title WizzleInfinityHelper contract
contract WizzleInfinityHelper is Mortal {
mapping (address => bool) public whitelisted;
ERC20 public token;
function WizzleInfinityHelper(address _token) public {
token = ERC20(_token);
}
/// @dev Whitelist a single address
/// @param addr Address to be whitelisted
function whitelist(address addr) public onlyOwner {
require(!whitelisted[addr]);
whitelisted[addr] = true;
}
/// @dev Remove an address from whitelist
/// @param addr Address to be removed from whitelist
function unwhitelist(address addr) public onlyOwner {
require(whitelisted[addr]);
whitelisted[addr] = false;
}
/// @dev Whitelist array of addresses
/// @param arr Array of addresses to be whitelisted
function bulkWhitelist(address[] arr) public onlyOwner {
for (uint i = 0; i < arr.length; i++) {
whitelisted[arr[i]] = true;
}
}
/// @dev Check if address is whitelisted
/// @param addr Address to be checked if it is whitelisted
/// @return Is address whitelisted?
function isWhitelisted(address addr) public constant returns (bool) {
return whitelisted[addr];
}
/// @dev Transfer tokens to addresses registered for airdrop
/// @param dests Array of addresses that have registered for airdrop
/// @param values Array of token amount for each address that have registered for airdrop
/// @return Number of transfers
function airdrop(address[] dests, uint256[] values) public onlyOwner returns (uint256) {
uint256 i = 0;
while (i < dests.length) {
token.transfer(dests[i], values[i]);
whitelisted[dests[i]] = true;
i += 1;
}
return (i);
}
}
|
Remove an address from whitelist addr Address to be removed from whitelist
|
function unwhitelist(address addr) public onlyOwner {
require(whitelisted[addr]);
whitelisted[addr] = false;
}
| 12,763,013
|
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "./interfaces/IValidatorShare.sol";
import "./interfaces/INodeOperatorRegistry.sol";
import "./interfaces/IStakeManager.sol";
import "./interfaces/IPoLidoNFT.sol";
import "./interfaces/IFxStateRootTunnel.sol";
import "./interfaces/IStMATIC.sol";
contract StMATIC is
IStMATIC,
ERC20Upgradeable,
AccessControlUpgradeable,
PausableUpgradeable
{
event SubmitEvent(address indexed _from, uint256 indexed _amount);
event RequestWithdrawEvent(address indexed _from, uint256 indexed _amount);
event DistributeRewardsEvent(uint256 indexed _amount);
event WithdrawTotalDelegatedEvent(
address indexed _from,
uint256 indexed _amount
);
event DelegateEvent(
uint256 indexed _amountDelegated,
uint256 indexed _remainder
);
event ClaimTokensEvent(
address indexed _from,
uint256 indexed _id,
uint256 indexed _amountClaimed,
uint256 _amountBurned
);
using SafeERC20Upgradeable for IERC20Upgradeable;
INodeOperatorRegistry public override nodeOperatorRegistry;
FeeDistribution public override entityFees;
IStakeManager public override stakeManager;
IPoLidoNFT public override poLidoNFT;
IFxStateRootTunnel public override fxStateRootTunnel;
string public override version;
address public override dao;
address public override insurance;
address public override token;
uint256 public override lastWithdrawnValidatorId;
uint256 public override totalBuffered;
uint256 public override delegationLowerBound;
uint256 public override rewardDistributionLowerBound;
uint256 public override reservedFunds;
uint256 public override submitThreshold;
bool public override submitHandler;
mapping(uint256 => RequestWithdraw) public override token2WithdrawRequest;
bytes32 public constant override DAO = keccak256("DAO");
/**
* @param _nodeOperatorRegistry - Address of the node operator registry
* @param _token - Address of MATIC token on Ethereum Mainnet
* @param _dao - Address of the DAO
* @param _insurance - Address of the insurance
* @param _stakeManager - Address of the stake manager
* @param _poLidoNFT - Address of the stMATIC NFT
* @param _fxStateRootTunnel - Address of the FxStateRootTunnel
*/
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external override initializer {
__AccessControl_init();
__Pausable_init();
__ERC20_init("Staked MATIC", "stMATIC");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DAO, _dao);
nodeOperatorRegistry = INodeOperatorRegistry(_nodeOperatorRegistry);
stakeManager = IStakeManager(_stakeManager);
poLidoNFT = IPoLidoNFT(_poLidoNFT);
fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
dao = _dao;
token = _token;
insurance = _insurance;
entityFees = FeeDistribution(25, 50, 25);
submitThreshold = _submitThreshold;
submitHandler = true;
}
/**
* @dev Send funds to StMATIC contract and mints StMATIC to msg.sender
* @notice Requires that msg.sender has approved _amount of MATIC to this contract
* @param _amount - Amount of MATIC sent from msg.sender to this contract
* @return Amount of StMATIC shares generated
*/
function submit(uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
require(_amount > 0, "Invalid amount");
if (submitHandler) {
require(
_amount + getTotalPooledMatic() <= submitThreshold,
"Submit threshold reached"
);
}
IERC20Upgradeable(token).safeTransferFrom(
msg.sender,
address(this),
_amount
);
(
uint256 amountToMint,
uint256 totalShares,
uint256 totalPooledMatic
) = convertMaticToStMatic(_amount);
_mint(msg.sender, amountToMint);
totalBuffered += _amount;
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalShares + amountToMint, totalPooledMatic + _amount)
);
emit SubmitEvent(msg.sender, _amount);
return amountToMint;
}
/**
* @dev Stores users request to withdraw into a RequestWithdraw struct
* @param _amount - Amount of StMATIC that is requested to withdraw
*/
function requestWithdraw(uint256 _amount) external override whenNotPaused {
require(_amount > 0, "Invalid amount");
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
uint256 operatorInfosLength = operatorInfos.length;
uint256 tokenId;
(
uint256 totalAmount2WithdrawInMatic,
uint256 totalShares,
uint256 totalPooledMATIC
) = convertStMaticToMatic(_amount);
uint256 currentAmount2WithdrawInMatic = totalAmount2WithdrawInMatic;
uint256 totalDelegated = getTotalStakeAcrossAllValidators();
uint256 minValidatorBalance = _getMinValidatorBalance(operatorInfos);
uint256 allowedAmount2RequestFromValidators = 0;
if (totalDelegated != 0) {
require(
(totalDelegated + totalBuffered) >=
currentAmount2WithdrawInMatic +
minValidatorBalance *
operatorInfosLength,
"Too much to withdraw"
);
allowedAmount2RequestFromValidators =
totalDelegated -
minValidatorBalance *
operatorInfosLength;
} else {
require(
totalBuffered >= currentAmount2WithdrawInMatic,
"Too much to withdraw"
);
}
while (currentAmount2WithdrawInMatic != 0) {
tokenId = poLidoNFT.mint(msg.sender);
if (allowedAmount2RequestFromValidators != 0) {
if (lastWithdrawnValidatorId > operatorInfosLength - 1) {
lastWithdrawnValidatorId = 0;
}
address validatorShare = operatorInfos[lastWithdrawnValidatorId]
.validatorShare;
(uint256 validatorBalance, ) = IValidatorShare(validatorShare)
.getTotalStake(address(this));
if (validatorBalance <= minValidatorBalance) {
lastWithdrawnValidatorId++;
continue;
}
uint256 allowedAmount2Withdraw = validatorBalance -
minValidatorBalance;
uint256 amount2WithdrawFromValidator = (allowedAmount2Withdraw <=
currentAmount2WithdrawInMatic)
? allowedAmount2Withdraw
: currentAmount2WithdrawInMatic;
sellVoucher_new(
validatorShare,
amount2WithdrawFromValidator,
type(uint256).max
);
token2WithdrawRequest[tokenId] = RequestWithdraw(
0,
IValidatorShare(validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
validatorShare
);
allowedAmount2RequestFromValidators -= amount2WithdrawFromValidator;
currentAmount2WithdrawInMatic -= amount2WithdrawFromValidator;
lastWithdrawnValidatorId++;
} else {
token2WithdrawRequest[tokenId] = RequestWithdraw(
currentAmount2WithdrawInMatic,
0,
stakeManager.epoch() + stakeManager.withdrawalDelay(),
address(0)
);
reservedFunds += currentAmount2WithdrawInMatic;
currentAmount2WithdrawInMatic = 0;
}
}
_burn(msg.sender, _amount);
fxStateRootTunnel.sendMessageToChild(
abi.encode(
totalShares - _amount,
totalPooledMATIC - totalAmount2WithdrawInMatic
)
);
emit RequestWithdrawEvent(msg.sender, _amount);
}
/**
* @notice This will be included in the cron job
* @dev Delegates tokens to validator share contract
*/
function delegate() external override whenNotPaused {
require(
totalBuffered > delegationLowerBound + reservedFunds,
"Amount to delegate lower than minimum"
);
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(true, false);
uint256 operatorInfosLength = operatorInfos.length;
require(operatorInfosLength > 0, "No operator shares, cannot delegate");
uint256 availableAmountToDelegate = totalBuffered - reservedFunds;
uint256 maxDelegateLimitsSum;
uint256 remainder;
for (uint256 i = 0; i < operatorInfosLength; i++) {
maxDelegateLimitsSum += operatorInfos[i].maxDelegateLimit;
}
require(maxDelegateLimitsSum > 0, "maxDelegateLimitsSum=0");
uint256 totalToDelegatedAmount = maxDelegateLimitsSum <=
availableAmountToDelegate
? maxDelegateLimitsSum
: availableAmountToDelegate;
IERC20Upgradeable(token).safeApprove(address(stakeManager), 0);
IERC20Upgradeable(token).safeApprove(
address(stakeManager),
totalToDelegatedAmount
);
uint256 amountDelegated;
for (uint256 i = 0; i < operatorInfosLength; i++) {
uint256 amountToDelegatePerOperator = (operatorInfos[i]
.maxDelegateLimit * totalToDelegatedAmount) /
maxDelegateLimitsSum;
buyVoucher(
operatorInfos[i].validatorShare,
amountToDelegatePerOperator,
0
);
amountDelegated += amountToDelegatePerOperator;
}
remainder = availableAmountToDelegate - amountDelegated;
totalBuffered = remainder + reservedFunds;
emit DelegateEvent(amountDelegated, remainder);
}
/**
* @dev Claims tokens from validator share and sends them to the
* user if his request is in the userToWithdrawRequest
* @param _tokenId - Id of the token that wants to be claimed
*/
function claimTokens(uint256 _tokenId) external override whenNotPaused {
require(poLidoNFT.isApprovedOrOwner(msg.sender, _tokenId), "Not owner");
RequestWithdraw storage usersRequest = token2WithdrawRequest[_tokenId];
require(
stakeManager.epoch() >= usersRequest.requestEpoch,
"Not able to claim yet"
);
poLidoNFT.burn(_tokenId);
uint256 amountToClaim;
if (usersRequest.validatorAddress != address(0)) {
uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(
address(this)
);
unstakeClaimTokens_new(
usersRequest.validatorAddress,
usersRequest.validatorNonce
);
amountToClaim =
IERC20Upgradeable(token).balanceOf(address(this)) -
balanceBeforeClaim;
} else {
amountToClaim = usersRequest.amount2WithdrawFromStMATIC;
reservedFunds -= amountToClaim;
totalBuffered -= amountToClaim;
}
IERC20Upgradeable(token).safeTransfer(msg.sender, amountToClaim);
emit ClaimTokensEvent(msg.sender, _tokenId, amountToClaim, 0);
}
/**
* @dev Distributes rewards claimed from validator shares based on fees defined in entityFee
*/
function distributeRewards() external override whenNotPaused {
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(true, false);
uint256 operatorInfosLength = operatorInfos.length;
for (uint256 i = 0; i < operatorInfosLength; i++) {
IValidatorShare validatorShare = IValidatorShare(
operatorInfos[i].validatorShare
);
uint256 stMaticReward = validatorShare.getLiquidRewards(
address(this)
);
uint256 rewardThreshold = validatorShare.minAmount();
if (stMaticReward >= rewardThreshold) {
validatorShare.withdrawRewards();
}
}
uint256 totalRewards = (
(IERC20Upgradeable(token).balanceOf(address(this)) - totalBuffered)
) / 10;
require(
totalRewards > rewardDistributionLowerBound,
"Amount to distribute lower than minimum"
);
uint256 balanceBeforeDistribution = IERC20Upgradeable(token).balanceOf(
address(this)
);
uint256 daoRewards = (totalRewards * entityFees.dao) / 100;
uint256 insuranceRewards = (totalRewards * entityFees.insurance) / 100;
uint256 operatorsRewards = (totalRewards * entityFees.operators) / 100;
uint256 operatorReward = operatorsRewards / operatorInfosLength;
IERC20Upgradeable(token).safeTransfer(dao, daoRewards);
IERC20Upgradeable(token).safeTransfer(insurance, insuranceRewards);
for (uint256 i = 0; i < operatorInfosLength; i++) {
IERC20Upgradeable(token).safeTransfer(
operatorInfos[i].rewardAddress,
operatorReward
);
}
uint256 currentBalance = IERC20Upgradeable(token).balanceOf(
address(this)
);
uint256 totalDistributed = balanceBeforeDistribution - currentBalance;
// Add the remainder to totalBuffered
totalBuffered = currentBalance;
emit DistributeRewardsEvent(totalDistributed);
}
/**
* @notice Only NodeOperatorRegistry can call this function
* @dev Withdraws funds from unstaked validator
* @param _validatorShare - Address of the validator share that will be withdrawn
*/
function withdrawTotalDelegated(address _validatorShare) external override {
require(
msg.sender == address(nodeOperatorRegistry),
"Not a node operator"
);
(uint256 stakedAmount, ) = getTotalStake(
IValidatorShare(_validatorShare)
);
if (stakedAmount == 0) {
return;
}
uint256 tokenId = poLidoNFT.mint(address(this));
sellVoucher_new(_validatorShare, stakedAmount, type(uint256).max);
token2WithdrawRequest[tokenId] = RequestWithdraw(
uint256(0),
IValidatorShare(_validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
_validatorShare
);
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit WithdrawTotalDelegatedEvent(_validatorShare, stakedAmount);
}
/**
* @dev Claims tokens from validator share and sends them to the
* StMATIC contract
* @param _tokenId - Id of the token that is supposed to be claimed
*/
function claimTokens2StMatic(uint256 _tokenId)
external
override
whenNotPaused
{
RequestWithdraw storage lidoRequests = token2WithdrawRequest[_tokenId];
require(
poLidoNFT.ownerOf(_tokenId) == address(this),
"Not owner of the NFT"
);
poLidoNFT.burn(_tokenId);
require(
stakeManager.epoch() >= lidoRequests.requestEpoch,
"Not able to claim yet"
);
uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(
address(this)
);
unstakeClaimTokens_new(
lidoRequests.validatorAddress,
lidoRequests.validatorNonce
);
uint256 claimedAmount = IERC20Upgradeable(token).balanceOf(
address(this)
) - balanceBeforeClaim;
totalBuffered += claimedAmount;
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit ClaimTokensEvent(address(this), _tokenId, claimedAmount, 0);
}
/**
* @dev Flips the pause state
*/
function togglePause() external override onlyRole(DEFAULT_ADMIN_ROLE) {
paused() ? _unpause() : _pause();
}
////////////////////////////////////////////////////////////
///// ///
///// ***ValidatorShare API*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev API for delegated buying vouchers from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _amount - Amount of MATIC to use for buying vouchers
* @param _minSharesToMint - Minimum of shares that is bought with _amount of MATIC
* @return Actual amount of MATIC used to buy voucher, might differ from _amount because of _minSharesToMint
*/
function buyVoucher(
address _validatorShare,
uint256 _amount,
uint256 _minSharesToMint
) private returns (uint256) {
uint256 amountSpent = IValidatorShare(_validatorShare).buyVoucher(
_amount,
_minSharesToMint
);
return amountSpent;
}
/**
* @dev API for delegated restaking rewards to validatorShare
* @param _validatorShare - Address of validatorShare contract
*/
function restake(address _validatorShare) private {
IValidatorShare(_validatorShare).restake();
}
/**
* @dev API for delegated unstaking and claiming tokens from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _unbondNonce - Unbond nonce
*/
function unstakeClaimTokens_new(
address _validatorShare,
uint256 _unbondNonce
) private {
IValidatorShare(_validatorShare).unstakeClaimTokens_new(_unbondNonce);
}
/**
* @dev API for delegated selling vouchers from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _claimAmount - Amount of MATIC to claim
* @param _maximumSharesToBurn - Maximum amount of shares to burn
*/
function sellVoucher_new(
address _validatorShare,
uint256 _claimAmount,
uint256 _maximumSharesToBurn
) private {
IValidatorShare(_validatorShare).sellVoucher_new(
_claimAmount,
_maximumSharesToBurn
);
}
/**
* @dev API for getting total stake of this contract from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @return Total stake of this contract and MATIC -> share exchange rate
*/
function getTotalStake(IValidatorShare _validatorShare)
public
view
override
returns (uint256, uint256)
{
return _validatorShare.getTotalStake(address(this));
}
/**
* @dev API for liquid rewards of this contract from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @return Liquid rewards of this contract
*/
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
override
returns (uint256)
{
return _validatorShare.getLiquidRewards(address(this));
}
////////////////////////////////////////////////////////////
///// ///
///// ***Helpers & Utilities*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev Helper function for that returns total pooled MATIC
* @return Total pooled MATIC
*/
function getTotalStakeAcrossAllValidators()
public
view
override
returns (uint256)
{
uint256 totalStake;
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
uint256 operatorInfosLength = operatorInfos.length;
for (uint256 i = 0; i < operatorInfosLength; i++) {
(uint256 currValidatorShare, ) = getTotalStake(
IValidatorShare(operatorInfos[i].validatorShare)
);
totalStake += currValidatorShare;
}
return totalStake;
}
/**
* @dev Function that calculates total pooled Matic
* @return Total pooled Matic
*/
function getTotalPooledMatic() public view override returns (uint256) {
uint256 totalStaked = getTotalStakeAcrossAllValidators();
return totalStaked + totalBuffered - reservedFunds;
}
/**
* @dev Function that converts arbitrary stMATIC to Matic
* @param _balance - Balance in stMATIC
* @return Balance in Matic, totalShares and totalPooledMATIC
*/
function convertStMaticToMatic(uint256 _balance)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 totalShares = totalSupply();
totalShares = totalShares == 0 ? 1 : totalShares;
uint256 totalPooledMATIC = getTotalPooledMatic();
totalPooledMATIC = totalPooledMATIC == 0 ? 1 : totalPooledMATIC;
uint256 balanceInMATIC = (_balance * totalPooledMATIC) / totalShares;
return (balanceInMATIC, totalShares, totalPooledMATIC);
}
/**
* @dev Function that converts arbitrary Matic to stMATIC
* @param _balance - Balance in Matic
* @return Balance in stMATIC, totalShares and totalPooledMATIC
*/
function convertMaticToStMatic(uint256 _balance)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 totalShares = totalSupply();
totalShares = totalShares == 0 ? 1 : totalShares;
uint256 totalPooledMatic = getTotalPooledMatic();
totalPooledMatic = totalPooledMatic == 0 ? 1 : totalPooledMatic;
uint256 balanceInStMatic = (_balance * totalShares) / totalPooledMatic;
return (balanceInStMatic, totalShares, totalPooledMatic);
}
/**
* @dev Function that calculates minimal allowed validator balance (lower bound)
* @return Minimal validator balance in MATIC
*/
function getMinValidatorBalance() external view override returns (uint256) {
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
return _getMinValidatorBalance(operatorInfos);
}
function _getMinValidatorBalance(Operator.OperatorInfo[] memory operatorInfos) private view returns (uint256) {
uint256 operatorInfosLength = operatorInfos.length;
uint256 minValidatorBalance = type(uint256).max;
for (uint256 i = 0; i < operatorInfosLength; i++) {
(uint256 validatorShare, ) = getTotalStake(
IValidatorShare(operatorInfos[i].validatorShare)
);
// 10% of current validatorShare
uint256 minValidatorBalanceCurrent = validatorShare / 10;
if (
minValidatorBalanceCurrent != 0 &&
minValidatorBalanceCurrent < minValidatorBalance
) {
minValidatorBalance = minValidatorBalanceCurrent;
}
}
return minValidatorBalance;
}
////////////////////////////////////////////////////////////
///// ///
///// ***Setters*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev Function that sets entity fees
* @notice Callable only by dao
* @param _daoFee - DAO fee in %
* @param _operatorsFee - Operator fees in %
* @param _insuranceFee - Insurance fee in %
*/
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external override onlyRole(DAO) {
require(
_daoFee + _operatorsFee + _insuranceFee == 100,
"sum(fee)!=100"
);
entityFees.dao = _daoFee;
entityFees.operators = _operatorsFee;
entityFees.insurance = _insuranceFee;
}
/**
* @dev Function that sets new dao address
* @notice Callable only by dao
* @param _address - New dao address
*/
function setDaoAddress(address _address) external override onlyRole(DAO) {
revokeRole(DAO, dao);
dao = _address;
_setupRole(DAO, dao);
}
/**
* @dev Function that sets new insurance address
* @notice Callable only by dao
* @param _address - New insurance address
*/
function setInsuranceAddress(address _address)
external
override
onlyRole(DAO)
{
insurance = _address;
}
/**
* @dev Function that sets new node operator address
* @notice Only callable by dao
* @param _address - New node operator address
*/
function setNodeOperatorRegistryAddress(address _address)
external
override
onlyRole(DAO)
{
nodeOperatorRegistry = INodeOperatorRegistry(_address);
}
/**
* @dev Function that sets new lower bound for delegation
* @notice Only callable by dao
* @param _delegationLowerBound - New lower bound for delegation
*/
function setDelegationLowerBound(uint256 _delegationLowerBound)
external
override
onlyRole(DAO)
{
delegationLowerBound = _delegationLowerBound;
}
/**
* @dev Function that sets new lower bound for rewards distribution
* @notice Only callable by dao
* @param _rewardDistributionLowerBound - New lower bound for rewards distribution
*/
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external override onlyRole(DAO) {
rewardDistributionLowerBound = _rewardDistributionLowerBound;
}
/**
* @dev Function that sets the poLidoNFT address
* @param _poLidoNFT new poLidoNFT address
*/
function setPoLidoNFT(address _poLidoNFT) external override onlyRole(DAO) {
poLidoNFT = IPoLidoNFT(_poLidoNFT);
}
/**
* @dev Function that sets the fxStateRootTunnel address
* @param _fxStateRootTunnel address of fxStateRootTunnel
*/
function setFxStateRootTunnel(address _fxStateRootTunnel)
external
override
onlyRole(DAO)
{
fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
}
/**
* @dev Function that sets the submitThreshold
* @param _submitThreshold new value for submit threshold
*/
function setSubmitThreshold(uint256 _submitThreshold)
external
override
onlyRole(DAO)
{
submitThreshold = _submitThreshold;
}
/**
* @dev Function that sets the submitHandler value to its NOT value
*/
function flipSubmitHandler() external override onlyRole(DAO) {
submitHandler = !submitHandler;
}
/**
* @dev Function that sets the new version
* @param _version - New version that will be set
*/
function setVersion(string calldata _version)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
version = _version;
}
/**
* @dev Function that retrieves the amount of matic that will be claimed from the NFT token
* @param _tokenId - Id of the PolidoNFT
*/
function getMaticFromTokenId(uint256 _tokenId)
external
view
override
returns (uint256)
{
RequestWithdraw memory requestData = token2WithdrawRequest[_tokenId];
IValidatorShare validatorShare = IValidatorShare(
requestData.validatorAddress
);
uint256 validatorId = validatorShare.validatorId();
uint256 exchangeRatePrecision = validatorId < 8 ? 100 : 10**29;
uint256 withdrawExchangeRate = validatorShare.withdrawExchangeRate();
IValidatorShare.DelegatorUnbond memory unbond = validatorShare
.unbonds_new(address(this), requestData.validatorNonce);
return (withdrawExchangeRate * unbond.shares) / exchangeRatePrecision;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/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 Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
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(IAccessControlUpgradeable).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 ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IValidatorShare {
struct DelegatorUnbond {
uint256 shares;
uint256 withdrawEpoch;
}
function unbondNonces(address _address) external view returns (uint256);
function activeAmount() external view returns (uint256);
function validatorId() external view returns (uint256);
function withdrawExchangeRate() external view returns (uint256);
function withdrawRewards() external;
function unstakeClaimTokens() external;
function minAmount() external view returns (uint256);
function getLiquidRewards(address user) external view returns (uint256);
function delegation() external view returns (bool);
function updateDelegation(bool _delegation) external;
function buyVoucher(uint256 _amount, uint256 _minSharesToMint)
external
returns (uint256);
function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn)
external;
function unstakeClaimTokens_new(uint256 unbondNonce) external;
function unbonds_new(address _address, uint256 _unbondNonce)
external
view
returns (DelegatorUnbond memory);
function getTotalStake(address user)
external
view
returns (uint256, uint256);
function owner() external view returns (address);
function restake() external returns (uint256, uint256);
function unlock() external;
function lock() external;
function drain(
address token,
address payable destination,
uint256 amount
) external;
function slash(uint256 _amount) external;
function migrateOut(address user, uint256 amount) external;
function migrateIn(address user, uint256 amount) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../lib/Operator.sol";
/// @title INodeOperatorRegistry
/// @author 2021 ShardLabs
/// @notice Node operator registry interface
interface INodeOperatorRegistry {
/// @notice Allows to add a new node operator to the system.
/// @param _name the node operator name.
/// @param _rewardAddress public address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
) external;
/// @notice Allows to stop a node operator.
/// @param _operatorId node operator id.
function stopOperator(uint256 _operatorId) external;
/// @notice Allows to remove a node operator from the system.
/// @param _operatorId node operator id.
function removeOperator(uint256 _operatorId) external;
/// @notice Allows a staked validator to join the system.
function joinOperator() external;
/// @notice Allows to stake an operator on the Polygon stakeManager.
/// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee)
/// has to be approved first.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdallFee to stake.
function stake(uint256 _amount, uint256 _heimdallFee) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param _amount amount to stake.
/// @param _restakeRewards restake rewards.
function restake(uint256 _amount, bool _restakeRewards) external;
/// @notice Allows the operator's owner to migrate the NFT. This can be done only
/// if the DAO stopped the operator.
function migrate() external;
/// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay
/// the operator owner can call claimStake func to withdraw the staked tokens.
function unstake() external;
/// @notice Allows to topup heimdall fees on polygon stakeManager.
/// @param _heimdallFee amount to topup.
function topUpForFee(uint256 _heimdallFee) external;
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
function unstakeClaim() external;
/// @notice Allows an owner to withdraw rewards from the stakeManager.
function withdrawRewards() external;
/// @notice Allows to update the signer pubkey
/// @param _signerPubkey update signer public key
function updateSigner(bytes memory _signerPubkey) external;
/// @notice Allows to claim the heimdall fees staked by the owner of the operator
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED
function unjail() external;
/// @notice Allows an operator's owner to set the operator name.
function setOperatorName(string memory _name) external;
/// @notice Allows an operator's owner to set the operator rewardAddress.
function setOperatorRewardAddress(address _rewardAddress) external;
/// @notice Allows the DAO to set _defaultMaxDelegateLimit.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external;
/// @notice Allows the DAO to set _maxDelegateLimit for an operator.
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external;
/// @notice Allows the DAO to set _commissionRate.
function setCommissionRate(uint256 _commissionRate) external;
/// @notice Allows the DAO to set _commissionRate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees.
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
) external;
/// @notice Allows to pause/unpause the node operator contract.
function togglePause() external;
/// @notice Allows the DAO to enable/disable restake.
function setRestake(bool _restake) external;
/// @notice Allows the DAO to set stMATIC contract.
function setStMATIC(address _stMATIC) external;
/// @notice Allows the DAO to set validator factory contract.
function setValidatorFactory(address _validatorFactory) external;
/// @notice Allows the DAO to set stake manager contract.
function setStakeManager(address _stakeManager) external;
/// @notice Allows to set contract version.
function setVersion(string memory _version) external;
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
);
/// @notice Allows to get stats.
function getState()
external
view
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalSlashedNodeOperator,
uint256 _totalEjectedNodeOperator
);
/// @notice Allows to get a list of operatorInfo.
function getOperatorInfos(bool _delegation, bool _allActive)
external
view
returns (Operator.OperatorInfo[] memory);
/// @notice Allows to get all the operator ids.
function getOperatorIds() external view returns (uint256[] memory);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
/// @title polygon stake manager interface.
/// @author 2021 ShardLabs
/// @notice User to interact with the polygon stake manager.
interface IStakeManager {
/// @notice Stake a validator on polygon stake manager.
/// @param user user that own the validator in our case the validator contract.
/// @param amount amount to stake.
/// @param heimdallFee heimdall fees.
/// @param acceptDelegation accept delegation.
/// @param signerPubkey signer publickey used in heimdall node.
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
function restake(
uint256 validatorId,
uint256 amount,
bool stakeRewards
) external;
/// @notice Request unstake a validator.
/// @param validatorId validator id.
function unstake(uint256 validatorId) external;
/// @notice Increase the heimdall fees.
/// @param user user that own the validator in our case the validator contract.
/// @param heimdallFee heimdall fees.
function topUpForFee(address user, uint256 heimdallFee) external;
/// @notice Get the validator id using the user address.
/// @param user user that own the validator in our case the validator contract.
/// @return return the validator id
function getValidatorId(address user) external view returns (uint256);
/// @notice get the validator contract used for delegation.
/// @param validatorId validator id.
/// @return return the address of the validator contract.
function getValidatorContract(uint256 validatorId)
external
view
returns (address);
/// @notice Withdraw accumulated rewards
/// @param validatorId validator id.
function withdrawRewards(uint256 validatorId) external;
/// @notice Get validator total staked.
/// @param validatorId validator id.
function validatorStake(uint256 validatorId)
external
view
returns (uint256);
/// @notice Allows to unstake the staked tokens on the stakeManager.
/// @param validatorId validator id.
function unstakeClaim(uint256 validatorId) external;
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
function updateSigner(uint256 _validatorId, bytes memory _signerPubkey)
external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId id of the validator that is to be unjailed
function unjail(uint256 _validatorId) external;
/// @notice Returns a withdrawal delay.
function withdrawalDelay() external view returns (uint256);
/// @notice Transfers amount from delegator
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function epoch() external view returns (uint256);
enum Status {
Inactive,
Active,
Locked,
Unstaked
}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
uint256 commissionRate;
uint256 lastCommissionUpdate;
uint256 delegatorsReward;
uint256 delegatedAmount;
uint256 initialRewardPerStake;
}
function validators(uint256 _index)
external
view
returns (Validator memory);
/// @notice Returns the address of the nft contract
function NFTContract() external view returns (address);
/// @notice Returns the validator accumulated rewards on stake manager.
function validatorReward(uint256 validatorId)
external
view
returns (uint256);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @title PoLidoNFT interface.
/// @author 2021 ShardLabs
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IFxStateRootTunnel {
function latestData() external view returns (bytes memory);
function setFxChildTunnel(address _fxChildTunnel) external;
function sendMessageToChild(bytes memory message) external;
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IValidatorShare.sol";
import "./INodeOperatorRegistry.sol";
import "./INodeOperatorRegistry.sol";
import "./IStakeManager.sol";
import "./IPoLidoNFT.sol";
import "./IFxStateRootTunnel.sol";
/// @title StMATIC interface.
/// @author 2021 ShardLabs
interface IStMATIC is IERC20Upgradeable {
struct RequestWithdraw {
uint256 amount2WithdrawFromStMATIC;
uint256 validatorNonce;
uint256 requestEpoch;
address validatorAddress;
}
struct FeeDistribution {
uint8 dao;
uint8 operators;
uint8 insurance;
}
function withdrawTotalDelegated(address _validatorShare) external;
function nodeOperatorRegistry() external returns (INodeOperatorRegistry);
function entityFees()
external
returns (
uint8,
uint8,
uint8
);
function getMaticFromTokenId(uint256 _tokenId)
external
view
returns (uint256);
function stakeManager() external view returns (IStakeManager);
function poLidoNFT() external view returns (IPoLidoNFT);
function fxStateRootTunnel() external view returns (IFxStateRootTunnel);
function version() external view returns (string memory);
function dao() external view returns (address);
function insurance() external view returns (address);
function token() external view returns (address);
function lastWithdrawnValidatorId() external view returns (uint256);
function totalBuffered() external view returns (uint256);
function delegationLowerBound() external view returns (uint256);
function rewardDistributionLowerBound() external view returns (uint256);
function reservedFunds() external view returns (uint256);
function submitThreshold() external view returns (uint256);
function submitHandler() external view returns (bool);
function getMinValidatorBalance() external view returns (uint256);
function token2WithdrawRequest(uint256 _requestId)
external
view
returns (
uint256,
uint256,
uint256,
address
);
function DAO() external view returns (bytes32);
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external;
function submit(uint256 _amount) external returns (uint256);
function requestWithdraw(uint256 _amount) external;
function delegate() external;
function claimTokens(uint256 _tokenId) external;
function distributeRewards() external;
function claimTokens2StMatic(uint256 _tokenId) external;
function togglePause() external;
function getTotalStake(IValidatorShare _validatorShare)
external
view
returns (uint256, uint256);
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
returns (uint256);
function getTotalStakeAcrossAllValidators() external view returns (uint256);
function getTotalPooledMatic() external view returns (uint256);
function convertStMaticToMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function convertMaticToStMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external;
function setDaoAddress(address _address) external;
function setInsuranceAddress(address _address) external;
function setNodeOperatorRegistryAddress(address _address) external;
function setDelegationLowerBound(uint256 _delegationLowerBound) external;
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external;
function setPoLidoNFT(address _poLidoNFT) external;
function setFxStateRootTunnel(address _fxStateRootTunnel) external;
function setSubmitThreshold(uint256 _submitThreshold) external;
function flipSubmitHandler() external;
function setVersion(string calldata _version) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
library Operator {
struct OperatorInfo {
uint256 operatorId;
address validatorShare;
uint256 maxDelegateLimit;
address rewardAddress;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
|
Send funds to StMATIC contract and mints StMATIC to msg.sender Requires that msg.sender has approved _amount of MATIC to this contract _amount - Amount of MATIC sent from msg.sender to this contract return Amount of StMATIC shares generated/
|
function submit(uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
require(_amount > 0, "Invalid amount");
if (submitHandler) {
require(
_amount + getTotalPooledMatic() <= submitThreshold,
"Submit threshold reached"
);
}
IERC20Upgradeable(token).safeTransferFrom(
msg.sender,
address(this),
_amount
);
(
uint256 amountToMint,
uint256 totalShares,
uint256 totalPooledMatic
) = convertMaticToStMatic(_amount);
_mint(msg.sender, amountToMint);
totalBuffered += _amount;
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalShares + amountToMint, totalPooledMatic + _amount)
);
emit SubmitEvent(msg.sender, _amount);
return amountToMint;
}
| 5,895,436
|
//Before life even began, before even the cosmos took shape, there was Light ... and Void. In the form of a boundless prismatic sea, the Light swelled across all existence. The ocean of Light was dynamic and ever shifting. Yet as it expanded, some of its energies faded and dimmed, leaving behind pockets of cold nothingness. From the absence of Light in these spaces, a new power coalesced and came to be. This power was the Void, a dark and vampiric force driven to devour all energy, to twist creation inward to feed upon itself.
//Will be stealthin any second
//Rewards in Cult
//
//Last coin $CHM went to 3M, lets see if you find our TG.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _createInitialSupply(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
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);
}
}
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner, address _rewardToken) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner, address _rewardToken) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner, address _rewardToken) external view returns(uint256);
}
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner, address _rewardToken) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend(address _rewardToken) external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract DividendPayingToken is DividendPayingTokenInterface, DividendPayingTokenOptionalInterface, Ownable {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
mapping(address => uint256) internal magnifiedDividendPerShare;
address[] public rewardTokens;
address public nextRewardToken;
uint256 public rewardTokenCounter;
IUniswapV2Router02 public immutable uniswapV2Router;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => mapping(address => int256)) internal magnifiedDividendCorrections;
mapping(address => mapping(address => uint256)) internal withdrawnDividends;
mapping (address => uint256) public holderBalance;
uint256 public totalBalance;
mapping(address => uint256) public totalDividendsDistributed;
constructor(){
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // router 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
uniswapV2Router = _uniswapV2Router;
// Mainnet
rewardTokens.push(address(0xf0f9D895aCa5c8678f706FB8216fa22957685A13)); // CULT - 0 0xf0f9D895aCa5c8678f706FB8216fa22957685A13
nextRewardToken = rewardTokens[0];
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalBalance > 0);
uint256 initialBalance = IERC20(nextRewardToken).balanceOf(address(this));
buyTokens(msg.value, nextRewardToken);
uint256 newBalance = IERC20(nextRewardToken).balanceOf(address(this)).sub(initialBalance);
if (newBalance > 0) {
magnifiedDividendPerShare[nextRewardToken] = magnifiedDividendPerShare[nextRewardToken].add(
(newBalance).mul(magnitude) / totalBalance
);
emit DividendsDistributed(msg.sender, newBalance);
totalDividendsDistributed[nextRewardToken] = totalDividendsDistributed[nextRewardToken].add(newBalance);
}
rewardTokenCounter = rewardTokenCounter == rewardTokens.length - 1 ? 0 : rewardTokenCounter + 1;
nextRewardToken = rewardTokens[rewardTokenCounter];
}
// useful for buybacks or to reclaim any BNB on the contract in a way that helps holders.
function buyTokens(uint256 bnbAmountInWei, address rewardToken) internal {
// generate the uniswap pair path of weth -> eth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = rewardToken;
// make the swap
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: bnbAmountInWei}(
0, // accept any amount of Ethereum
path,
address(this),
block.timestamp
);
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend(address _rewardToken) external virtual override {
_withdrawDividendOfUser(payable(msg.sender), _rewardToken);
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user, address _rewardToken) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user, _rewardToken);
if (_withdrawableDividend > 0) {
withdrawnDividends[user][_rewardToken] = withdrawnDividends[user][_rewardToken].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
IERC20(_rewardToken).transfer(user, _withdrawableDividend);
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner, address _rewardToken) external view override returns(uint256) {
return withdrawableDividendOf(_owner, _rewardToken);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner, address _rewardToken) public view override returns(uint256) {
return accumulativeDividendOf(_owner,_rewardToken).sub(withdrawnDividends[_owner][_rewardToken]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner, address _rewardToken) external view override returns(uint256) {
return withdrawnDividends[_owner][_rewardToken];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner, address _rewardToken) public view override returns(uint256) {
return magnifiedDividendPerShare[_rewardToken].mul(holderBalance[_owner]).toInt256Safe()
.add(magnifiedDividendCorrections[_rewardToken][_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that increases tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _increase(address account, uint256 value) internal {
for (uint256 i; i < rewardTokens.length; i++){
magnifiedDividendCorrections[rewardTokens[i]][account] = magnifiedDividendCorrections[rewardTokens[i]][account]
.sub((magnifiedDividendPerShare[rewardTokens[i]].mul(value)).toInt256Safe());
}
}
/// @dev Internal function that reduces an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _reduce(address account, uint256 value) internal {
for (uint256 i; i < rewardTokens.length; i++){
magnifiedDividendCorrections[rewardTokens[i]][account] = magnifiedDividendCorrections[rewardTokens[i]][account]
.add( (magnifiedDividendPerShare[rewardTokens[i]].mul(value)).toInt256Safe() );
}
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = holderBalance[account];
holderBalance[account] = newBalance;
if(newBalance > currentBalance) {
uint256 increaseAmount = newBalance.sub(currentBalance);
_increase(account, increaseAmount);
totalBalance += increaseAmount;
} else if(newBalance < currentBalance) {
uint256 reduceAmount = currentBalance.sub(newBalance);
_reduce(account, reduceAmount);
totalBalance -= reduceAmount;
}
}
}
contract DividendTracker is DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(address key) private view returns (uint) {
return tokenHoldersMap.values[key];
}
function getIndexOfKey(address key) private view returns (int) {
if(!tokenHoldersMap.inserted[key]) {
return -1;
}
return int(tokenHoldersMap.indexOf[key]);
}
function getKeyAtIndex(uint index) private view returns (address) {
return tokenHoldersMap.keys[index];
}
function size() private view returns (uint) {
return tokenHoldersMap.keys.length;
}
function set(address key, uint val) private {
if (tokenHoldersMap.inserted[key]) {
tokenHoldersMap.values[key] = val;
} else {
tokenHoldersMap.inserted[key] = true;
tokenHoldersMap.values[key] = val;
tokenHoldersMap.indexOf[key] = tokenHoldersMap.keys.length;
tokenHoldersMap.keys.push(key);
}
}
function remove(address key) private {
if (!tokenHoldersMap.inserted[key]) {
return;
}
delete tokenHoldersMap.inserted[key];
delete tokenHoldersMap.values[key];
uint index = tokenHoldersMap.indexOf[key];
uint lastIndex = tokenHoldersMap.keys.length - 1;
address lastKey = tokenHoldersMap.keys[lastIndex];
tokenHoldersMap.indexOf[lastKey] = index;
delete tokenHoldersMap.indexOf[key];
tokenHoldersMap.keys[index] = lastKey;
tokenHoldersMap.keys.pop();
}
Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event IncludeInDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() {
claimWait = 1200;
minimumTokenBalanceForDividends = 1000 * (10**18);
}
function excludeFromDividends(address account) external onlyOwner {
excludedFromDividends[account] = true;
_setBalance(account, 0);
remove(account);
emit ExcludeFromDividends(account);
}
function includeInDividends(address account) external onlyOwner {
require(excludedFromDividends[account]);
excludedFromDividends[account] = false;
emit IncludeInDividends(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 1200 && newClaimWait <= 86400, "Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
// Check to see if I really made this contract or if it is a clone!
// @Sir_Tris on TG, @SirTrisCrypto on Twitter
function getAccount(address _account, address _rewardToken)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account, _rewardToken);
totalDividends = accumulativeDividendOf(account, _rewardToken);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index, address _rewardToken)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = getKeyAtIndex(index);
return getAccount(account, _rewardToken);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
set(account, newBalance);
}
else {
_setBalance(account, 0);
remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount;
bool paid;
for (uint256 i; i < rewardTokens.length; i++){
amount = _withdrawDividendOfUser(account, rewardTokens[i]);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
paid = true;
}
}
return paid;
}
}
contract Warlock is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
DividendTracker public dividendTracker;
address public operationsWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public liquidityActiveBlock = 0; // 0 means liquidity is not active yet
uint256 public tradingActiveBlock = 0; // 0 means trading is not active
uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public constant feeDivisor = 1000;
uint256 public totalSellFees;
uint256 public rewardsSellFee;
uint256 public operationsSellFee;
uint256 public liquiditySellFee;
uint256 public totalBuyFees;
uint256 public rewardsBuyFee;
uint256 public operationsBuyFee;
uint256 public liquidityBuyFee;
uint256 public tokensForRewards;
uint256 public tokensForOperations;
uint256 public tokensForLiquidity;
uint256 public gasForProcessing = 0;
uint256 public lpWithdrawRequestTimestamp;
uint256 public lpWithdrawRequestDuration = 3 days;
bool public lpWithdrawRequestPending;
uint256 public lpPercToWithDraw;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event ExcludedMaxTransactionAmount(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event OperationsWalletUpdated(address indexed newWallet, address indexed oldWallet);
event DevWalletUpdated(address indexed newWallet, address indexed oldWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SendDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
event RequestedLPWithdraw();
event WithdrewLPForMigration();
event CanceledLpWithdrawRequest();
constructor() ERC20("WARLOCK", "WARLOCK") {
uint256 totalSupply = 100 * 1e6 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn
swapTokensAtAmount = totalSupply * 10 / 10000; // 1% swap tokens amount
maxWallet = totalSupply * 2 / 100; // 2% Max wallet
rewardsBuyFee = 10;
operationsBuyFee = 100;
liquidityBuyFee = 5;
totalBuyFees = rewardsBuyFee + operationsBuyFee + liquidityBuyFee;
rewardsSellFee = 10;
operationsSellFee = 100;
liquiditySellFee = 5;
totalSellFees = rewardsSellFee + operationsSellFee + liquiditySellFee;
dividendTracker = new DividendTracker();
operationsWallet = address(msg.sender); // set as operations wallet
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0xdead));
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(dividendTracker), true);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
excludeFromMaxTransaction(address(0xdead), true);
_createInitialSupply(address(owner()), totalSupply);
}
receive() external payable {
}
// only use if conducting a presale
function addPresaleAddressForExclusions(address _presaleAddress) external onlyOwner {
excludeFromFees(_presaleAddress, true);
dividendTracker.excludeFromDividends(_presaleAddress);
excludeFromMaxTransaction(_presaleAddress, true);
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// excludes wallets and contracts from dividends (such as CEX hotwallets, etc.)
function excludeFromDividends(address account) external onlyOwner {
dividendTracker.excludeFromDividends(account);
}
// removes exclusion on wallets and contracts from dividends (such as CEX hotwallets, etc.)
function includeInDividends(address account) external onlyOwner {
dividendTracker.includeInDividends(account);
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
require(!tradingActive, "Cannot re-enable trading");
tradingActive = true;
swapEnabled = true;
tradingActiveBlock = block.number;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateMaxAmount(uint256 newNum) external onlyOwner {
require(newNum > (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum > (totalSupply() * 1 / 100)/1e18, "Cannot set maxWallet lower than 1%");
maxWallet = newNum * (10**18);
}
function updateBuyFees(uint256 _operationsFee, uint256 _rewardsFee, uint256 _liquidityFee) external onlyOwner {
operationsBuyFee = _operationsFee;
rewardsBuyFee = _rewardsFee;
liquidityBuyFee = _liquidityFee;
totalBuyFees = operationsBuyFee + rewardsBuyFee + liquidityBuyFee;
require(totalBuyFees <= 200, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _operationsFee, uint256 _rewardsFee, uint256 _liquidityFee) external onlyOwner {
operationsSellFee = _operationsFee;
rewardsSellFee = _rewardsFee;
liquiditySellFee = _liquidityFee;
totalSellFees = operationsSellFee + rewardsSellFee + liquiditySellFee;
require(totalSellFees <= 300, "Must keep fees at 30% or less");
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
emit ExcludedMaxTransactionAmount(updAds, isEx);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) external onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner {
require(pair != uniswapV2Pair, "The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
excludeFromMaxTransaction(pair, value);
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateOperationsWallet(address newOperationsWallet) external onlyOwner {
require(newOperationsWallet != address(0), "may not set to 0 address");
excludeFromFees(newOperationsWallet, true);
emit OperationsWalletUpdated(newOperationsWallet, operationsWallet);
operationsWallet = newOperationsWallet;
}
function updateGasForProcessing(uint256 newValue) external onlyOwner {
require(newValue >= 200000 && newValue <= 500000, " gasForProcessing must be between 200,000 and 500,000");
require(newValue != gasForProcessing, "Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed(address rewardToken) external view returns (uint256) {
return dividendTracker.totalDividendsDistributed(rewardToken);
}
function isExcludedFromFees(address account) external view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account, address rewardToken) external view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account, rewardToken);
}
function dividendTokenBalanceOf(address account) external view returns (uint256) {
return dividendTracker.holderBalance(account);
}
function getAccountDividendsInfo(address account, address rewardToken)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account, rewardToken);
}
function getAccountDividendsInfoAtIndex(uint256 index, address rewardToken)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index, rewardToken);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function getNumberOfDividends() external view returns(uint256) {
return dividendTracker.totalBalance();
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
transferDelayEnabled = false;
return true;
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet.");
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]) {
require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// no taxes on transfers (non buys/sells)
if(takeFee){
if(tradingActiveBlock + 1 >= block.number && (automatedMarketMakerPairs[to] || automatedMarketMakerPairs[from])){
fees = amount.mul(99).div(100);
tokensForLiquidity += fees * 33 / 99;
tokensForRewards += fees * 33 / 99;
tokensForOperations += fees * 33 / 99;
}
// on sell
else if (automatedMarketMakerPairs[to] && totalSellFees > 0){
fees = amount.mul(totalSellFees).div(feeDivisor);
tokensForRewards += fees * rewardsSellFee / totalSellFees;
tokensForLiquidity += fees * liquiditySellFee / totalSellFees;
tokensForOperations += fees * operationsSellFee / totalSellFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) {
fees = amount.mul(totalBuyFees).div(feeDivisor);
tokensForRewards += fees * rewardsBuyFee / totalBuyFees;
tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees;
tokensForOperations += fees * operationsBuyFee / totalBuyFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
dividendTracker.setBalance(payable(from), balanceOf(from));
dividendTracker.setBalance(payable(to), balanceOf(to));
if(!swapping && gasForProcessing > 0) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
}
catch {}
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(0xdead),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForRewards;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap - (tokensForLiquidity/2));
uint256 ethForRewards = ethBalance.mul(tokensForRewards).div(totalTokensToSwap - (tokensForLiquidity/2));
uint256 ethForLiquidity = ethBalance - ethForOperations - ethForRewards;
tokensForLiquidity = 0;
tokensForOperations = 0;
tokensForRewards = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
// call twice to force buy of both reward tokens.
(bool success,) = address(dividendTracker).call{value: ethForRewards}("");
(success,) = address(operationsWallet).call{value: address(this).balance}("");
}
function withdrawStuckEth() external onlyOwner {
(bool success,) = address(msg.sender).call{value: address(this).balance}("");
require(success, "failed to withdraw");
}
function requestToWithdrawLP(uint256 percToWithdraw) external onlyOwner {
require(!lpWithdrawRequestPending, "Cannot request again until first request is over.");
require(percToWithdraw <= 100 && percToWithdraw > 0, "Need to set between 1-100%");
lpWithdrawRequestTimestamp = block.timestamp;
lpWithdrawRequestPending = true;
lpPercToWithDraw = percToWithdraw;
emit RequestedLPWithdraw();
}
function nextAvailableLpWithdrawDate() public view returns (uint256){
if(lpWithdrawRequestPending){
return lpWithdrawRequestTimestamp + lpWithdrawRequestDuration;
}
else {
return 0; // 0 means no open requests
}
}
function withdrawRequestedLP() external onlyOwner {
require(block.timestamp >= nextAvailableLpWithdrawDate() && nextAvailableLpWithdrawDate() > 0, "Must request and wait.");
lpWithdrawRequestTimestamp = 0;
lpWithdrawRequestPending = false;
uint256 amtToWithdraw = IERC20(address(uniswapV2Pair)).balanceOf(address(this)) * lpPercToWithDraw / 100;
lpPercToWithDraw = 0;
IERC20(uniswapV2Pair).transfer(msg.sender, amtToWithdraw);
}
function cancelLPWithdrawRequest() external onlyOwner {
lpWithdrawRequestPending = false;
lpPercToWithDraw = 0;
lpWithdrawRequestTimestamp = 0;
emit CanceledLpWithdrawRequest();
}
}
|
useful for buybacks or to reclaim any BNB on the contract in a way that helps holders. generate the uniswap pair path of weth -> eth make the swap
|
function buyTokens(uint256 bnbAmountInWei, address rewardToken) internal {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = rewardToken;
path,
address(this),
block.timestamp
);
}
| 2,072,940
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./Context.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
import "./Owned.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 ERC20Farm is Context, IERC20, Owned {
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;
address public _minterContract;
address public _nftFarmingContract;
mapping (address => bool) private disabled_burn;
/**
* @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, address owner) public Owned(owner){
_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];
}
//set contract account that can mint and one that can farm
function setContracts(address minterContract, address nftFarmingContract) external onlyOwner returns (bool){
_minterContract=minterContract;
_nftFarmingContract=nftFarmingContract;
}
// to mint the YOU tokens by staking contract
function mintToFarm(uint256 amount) external payable onlyMinterContract returns (bool) {
_mint(msg.sender, amount);
return true;
}
// to burn YOU tokens by FarmingNFT contract
function burnToFarm(address account, uint256 amount) external onlynftFarmingContract returns (bool) {
require(disabled_burn[account] != true, "Account has disabled burning to be allowed by Farming contract");
_burn(account, amount);
return true;
}
// enable FarmingNFT contract to burn tokens
function enableFarmBurn() external returns (bool) {
require(disabled_burn[msg.sender] == true, "Account is already enabled burning to be allowed by Farming contract");
disabled_burn[msg.sender] = false;
return true;
}
// disable FarmingNFT contract to burn tokens:
// enabled by default
function disableFarmBurn() external returns (bool) {
require(disabled_burn[msg.sender] != true, "Account is already disabled burning to be allowed by Farming contract");
disabled_burn[msg.sender] = true;
return true;
}
/**
* @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 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);
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinterContract() {
require(isMinterContract(), "caller is not the minting staking contract");
_;
}
/**
* @dev Returns true if the caller is the current minter.
*/
function isMinterContract() public view returns (bool) {
return _msgSender() == _minterContract;
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlynftFarmingContract() {
require(isnftFarmingContract(), "caller is not the nft farming contract");
_;
}
/**
* @dev Returns true if the caller is the current nft farming contract.
*/
function isnftFarmingContract() public view returns (bool) {
return _msgSender() == _nftFarmingContract;
}
}
|
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);
}
| 1,447,436
|
/* Attestation decode and validation */
/* AlphaWallet 2021 - 2022 */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract VerifyTicket {
using ECDSA for bytes32;
address payable owner;
bytes1 constant BOOLEAN_TAG = bytes1(0x01);
bytes1 constant INTEGER_TAG = bytes1(0x02);
bytes1 constant BIT_STRING_TAG = bytes1(0x03);
bytes1 constant OCTET_STRING_TAG = bytes1(0x04);
bytes1 constant NULL_TAG = bytes1(0x05);
bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06);
bytes1 constant EXTERNAL_TAG = bytes1(0x08);
bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10
bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16
bytes1 constant SET_TAG = bytes1(0x11); // decimal 17
bytes1 constant SET_OF_TAG = bytes1(0x11);
bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18
bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19
bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20
bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21
bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22
bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23
bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24
bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25
bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26
bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27
bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28
bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30
bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12
bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28
bytes1 constant LENGTH_TAG = bytes1(0x30);
bytes1 constant VERSION_TAG = bytes1(0xA0);
bytes1 constant COMPOUND_TAG = bytes1(0xA3);
uint constant TTL_GAP = 300;// 5 min
uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content
uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID"));
uint256 constant public fieldSize = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant public curveOrder = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
event Value(uint256 indexed val);
event RtnStr(bytes val);
event RtnS(string val);
uint256[2] private G = [ 21282764439311451829394129092047993080259557426320933158672611067687630484067,
3813889942691430704369624600187664845713336792511424430006907067499686345744 ];
uint256[2] private H = [ 10844896013696871595893151490650636250667003995871483372134187278207473369077,
9393217696329481319187854592386054938412168121447413803797200472841959383227 ];
uint256 constant curveOrderBitLength = 254;
uint256 constant curveOrderBitShift = 256 - curveOrderBitLength;
uint256 constant pointLength = 65;
// We create byte arrays for these at construction time to save gas when we need to use them
bytes constant GPoint = abi.encodePacked(uint8(0x04), uint256(21282764439311451829394129092047993080259557426320933158672611067687630484067),
uint256(3813889942691430704369624600187664845713336792511424430006907067499686345744));
bytes constant HPoint = abi.encodePacked(uint8(0x04), uint256(10844896013696871595893151490650636250667003995871483372134187278207473369077),
uint256(9393217696329481319187854592386054938412168121447413803797200472841959383227));
bytes constant emptyBytes = new bytes(0x00);
struct FullProofOfExponent {
bytes tPoint;
uint256 challenge;
bytes entropy;
}
constructor()
{
owner = payable(msg.sender);
}
struct Length {
uint decodeIndex;
uint length;
}
/**
* Perform TicketAttestation verification
* NOTE: This function DOES NOT VALIDATE whether the public key attested to is the same as the one who signed this transaction; you must perform validation of the subject from the calling function.
**/
function verifyTicketAttestation(bytes memory attestation, address attestor, address ticketIssuer) external view returns(address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid)
{
address recoveredAttestor;
address recoveredIssuer;
(recoveredAttestor, recoveredIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation);
if (recoveredAttestor != attestor || recoveredIssuer != ticketIssuer || !attestationValid)
{
subject = address(0);
ticketId = emptyBytes;
conferenceId = emptyBytes;
attestationValid = false;
}
}
function verifyTicketAttestation(bytes memory attestation) external view returns(address attestor, address ticketIssuer, address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) //public pure returns(address payable subject, bytes memory ticketId, string memory identifier, address issuer, address attestor)
{
(attestor, ticketIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation);
}
function _verifyTicketAttestation(bytes memory attestation) public view returns(address attestor, address ticketIssuer, address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) //public pure returns(address payable subject, bytes memory ticketId, string memory identifier, address issuer, address attestor)
{
uint256 decodeIndex = 0;
uint256 length = 0;
FullProofOfExponent memory pok;
// Commitment to user identifier in Attestation
bytes memory commitment1;
// Commitment to user identifier in Ticket
bytes memory commitment2;
(length, decodeIndex, ) = decodeLength(attestation, 0); //852 (total length, primary header)
(ticketIssuer, ticketId, conferenceId, commitment2, decodeIndex) = recoverTicketSignatureAddress(attestation, decodeIndex);
(attestor, subject, commitment1, decodeIndex, attestationValid) = recoverSignedIdentifierAddress(attestation, decodeIndex);
//now pull ZK (Zero-Knowledge) POK (Proof Of Knowledge) data
(pok, decodeIndex) = recoverPOK(attestation, decodeIndex);
if (!attestationValid || !verifyPOK(commitment1, commitment2, pok))
{
attestor = address(0);
ticketIssuer = address(0);
subject = address(0);
ticketId = emptyBytes;
conferenceId = emptyBytes;
attestationValid = false;
}
}
function verifyEqualityProof(bytes memory com1, bytes memory com2, bytes memory proof, bytes memory entropy) public view returns(bool result)
{
FullProofOfExponent memory pok;
bytes memory attestationData;
uint256 decodeIndex = 0;
uint256 length = 0;
(length, decodeIndex, ) = decodeLength(proof, 0);
(, attestationData, decodeIndex,) = decodeElement(proof, decodeIndex);
pok.challenge = bytesToUint(attestationData);
(, pok.tPoint, decodeIndex,) = decodeElement(proof, decodeIndex);
pok.entropy = entropy;
return verifyPOK(com1, com2, pok);
}
//////////////////////////////////////////////////////////////
// DER Structure Decoding
//////////////////////////////////////////////////////////////
function recoverSignedIdentifierAddress(bytes memory attestation, uint256 hashIndex) public view returns(address signer, address subject, bytes memory commitment1, uint256 resultIndex, bool timeStampValid)
{
bytes memory sigData;
uint256 length ;
uint256 decodeIndex ;
uint256 headerIndex;
(length, hashIndex, ) = decodeLength(attestation, hashIndex); //576 (SignedIdentifierAttestation)
(length, headerIndex, ) = decodeLength(attestation, hashIndex); //493 (IdentifierAttestation)
resultIndex = length + headerIndex; // (length + decodeIndex) - hashIndex);
bytes memory preHash = copyDataBlock(attestation, hashIndex, (length + headerIndex) - hashIndex);
decodeIndex = headerIndex + length;
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Signature algorithm
(length, sigData, resultIndex) = decodeElementOffset(attestation, decodeIndex + length, 1); // Signature
//get signing address
signer = recoverSigner(preHash, sigData);
//Recover public key
(length, decodeIndex, ) = decodeLength(attestation, headerIndex); //read Version
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Serial
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Signature type (9) 1.2.840.10045.2.1
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(decodeIndex, timeStampValid) = decodeTimeBlock(attestation, decodeIndex + length);
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // Smartcontract?
(subject, decodeIndex) = addressFromPublicKey(attestation, decodeIndex + length);
commitment1 = decodeCommitment(attestation, decodeIndex);
}
function decodeCommitment (bytes memory attestation, uint256 decodeIndex) internal virtual pure returns (bytes memory commitment) {
uint256 length ;
bytes1 blockType = attestation[decodeIndex];
if (blockType != 0xa3) {
// its not commitment, but some other data. example: SEQUENCE (INTEGER 42, INTEGER 1337)
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // some payload
}
(commitment, ) = recoverCommitment(attestation, decodeIndex + length); // Commitment 1, generated by
// IdentifierAttestation constructor
}
function decodeTimeBlock(bytes memory attestation, uint256 decodeIndex) public view returns (uint256 index, bool valid)
{
bytes memory timeBlock;
uint256 length;
uint256 blockLength;
bytes1 tag;
(blockLength, index, ) = decodeLength(attestation, decodeIndex); //30 32
(length, decodeIndex, ) = decodeLength(attestation, index); //18 0f
(length, timeBlock, decodeIndex, tag) = decodeElement(attestation, decodeIndex + length); //INTEGER_TAG if blockchain friendly time is used
if (tag == INTEGER_TAG)
{
uint256 startTime = bytesToUint(timeBlock);
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //18 0F
(, timeBlock, decodeIndex,) = decodeElement(attestation, decodeIndex + length);
uint256 endTime = bytesToUint(timeBlock);
valid = block.timestamp > (startTime - TTL_GAP) && block.timestamp < endTime;
}
else
{
valid = false; //fail attestation without blockchain friendly timestamps
}
index = index + blockLength;
}
function recoverCommitment(bytes memory attestation, uint256 decodeIndex) internal pure returns(bytes memory commitment, uint256 resultIndex)
{
uint256 length;
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // Commitment tag (0x57)
//pull Commitment
commitment = copyDataBlock(attestation, decodeIndex + (length - 65), 65);
resultIndex = decodeIndex + length;
}
function recoverTicketSignatureAddress(bytes memory attestation, uint256 hashIndex) public pure returns(address signer, bytes memory ticketId, bytes memory conferenceId, bytes memory commitment2, uint256 resultIndex)
{
uint256 length;
uint256 decodeIndex;
bytes memory sigData;
(length, decodeIndex, ) = decodeLength(attestation, hashIndex); //163 Ticket Data
(length, hashIndex, ) = decodeLength(attestation, decodeIndex); //5D
bytes memory preHash = copyDataBlock(attestation, decodeIndex, (length + hashIndex) - decodeIndex); // ticket
(length, conferenceId, decodeIndex, ) = decodeElement(attestation, hashIndex); //CONFERENCE_ID
(length, ticketId, decodeIndex,) = decodeElement(attestation, decodeIndex); //TICKET_ID
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Ticket Class
(length, commitment2, decodeIndex,) = decodeElement(attestation, decodeIndex + length); // Commitment 2, generated by Ticket constructor
// in class Ticket
(length, sigData, resultIndex) = decodeElementOffset(attestation, decodeIndex, 1); // Signature
//ecrecover
signer = recoverSigner(preHash, sigData);
}
function recoverPOK(bytes memory attestation, uint256 decodeIndex) private pure returns(FullProofOfExponent memory pok, uint256 resultIndex)
{
bytes memory data;
uint256 length;
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //68 POK data
(length, data, decodeIndex,) = decodeElement(attestation, decodeIndex);
pok.challenge = bytesToUint(data);
(length, pok.tPoint, decodeIndex,) = decodeElement(attestation, decodeIndex);
(length, pok.entropy, resultIndex,) = decodeElement(attestation, decodeIndex);
}
function getAttestationTimestamp(bytes memory attestation) public pure returns(string memory startTime, string memory endTime)
{
uint256 decodeIndex = 0;
uint256 length = 0;
(length, decodeIndex, ) = decodeLength(attestation, 0); //852 (total length, primary header)
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Ticket (should be 163)
(startTime, endTime) = getAttestationTimestamp(attestation, decodeIndex + length);
}
function getAttestationTimestamp(bytes memory attestation, uint256 decodeIndex) public pure returns(string memory startTime, string memory endTime)
{
uint256 length = 0;
bytes memory timeData;
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //576 (SignedIdentifierAttestation)
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //493 (IdentifierAttestation)
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //read Version
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Serial
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Signature type (9) 1.2.840.10045.2.1
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Validity time
(length, timeData, decodeIndex, ) = decodeElement(attestation, decodeIndex);
startTime = copyStringBlock(timeData);
(length, timeData, decodeIndex, ) = decodeElement(attestation, decodeIndex);
endTime = copyStringBlock(timeData);
}
function addressFromPublicKey(bytes memory attestation, uint256 decodeIndex) public pure returns(address keyAddress, uint256 resultIndex)
{
uint256 length;
bytes memory publicKeyBytes;
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // 307 key headerIndex
(length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // 236 header tag
(length, publicKeyBytes, resultIndex) = decodeElementOffset(attestation, decodeIndex + length, 2); // public key
keyAddress = publicKeyToAddress(publicKeyBytes);
}
//////////////////////////////////////////////////////////////
// Cryptography & Ethereum constructs
//////////////////////////////////////////////////////////////
function getRiddle(bytes memory com1, bytes memory com2) public view returns(uint256[2] memory riddle)
{
uint256[2] memory lhs;
uint256[2] memory rhs;
(lhs[0], lhs[1]) = extractXYFromPoint(com1);
(rhs[0], rhs[1]) = extractXYFromPoint(com2);
rhs = ecInv(rhs);
riddle = ecAdd(lhs, rhs);
}
/* Verify ZK (Zero-Knowledge) proof of equality of message in two
Pedersen commitments by proving knowledge of the discrete log
of their difference. This verifies that the message
(identifier, such as email address) in both commitments are the
same, and the one constructing the proof knows the secret of
both these commitments. See:
Commitment1: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/tokenscript/attestation/IdentifierAttestation.java
Commitment2: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/devcon/ticket/Ticket.java
Reference implementation: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/tokenscript/attestation/core/AttestationCrypto.java
*/
function verifyPOK(bytes memory com1, bytes memory com2, FullProofOfExponent memory pok) private view returns(bool)
{
// Riddle is H*(r1-r2) with r1, r2 being the secret randomness of com1, respectively com2
uint256[2] memory riddle = getRiddle(com1, com2);
// Compute challenge in a Fiat-Shamir style, based on context specific entropy to avoid reuse of proof
bytes memory cArray = abi.encodePacked(HPoint, com1, com2, pok.tPoint, pok.entropy);
uint256 c = mapToCurveMultiplier(cArray);
uint256[2] memory lhs = ecMul(pok.challenge, H[0], H[1]);
if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas
//ECPoint riddle multiply by proof (component hash)
uint256[2] memory rhs = ecMul(c, riddle[0], riddle[1]);
if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas
uint256[2] memory point;
(point[0], point[1]) = extractXYFromPoint(pok.tPoint);
rhs = ecAdd(rhs, point);
return ecEquals(lhs, rhs);
}
function ecEquals(uint256[2] memory ecPoint1, uint256[2] memory ecPoint2) private pure returns(bool)
{
return (ecPoint1[0] == ecPoint2[0] && ecPoint1[1] == ecPoint2[1]);
}
function publicKeyToAddress(bytes memory publicKey) pure internal returns(address keyAddr)
{
bytes32 keyHash = keccak256(publicKey);
bytes memory scratch = new bytes(32);
assembly {
mstore(add(scratch, 32), keyHash)
mstore(add(scratch, 12), 0)
keyAddr := mload(add(scratch, 32))
}
}
function recoverSigner(bytes memory prehash, bytes memory signature) internal pure returns(address signer)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(signature);
return ecrecover(keccak256(prehash), v, r, s);
}
function splitSignature(bytes memory sig)
internal pure returns (bytes32 r, bytes32 s, uint8 v)
{
require(sig.length == 65, "invalid signature length");
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)))
}
}
function ecMul(uint256 s, uint256 x, uint256 y) public view
returns (uint256[2] memory retP)
{
bool success;
// With a public key (x, y), this computes p = scalar * (x, y).
uint256[3] memory i = [x, y, s];
assembly
{
// call ecmul precompile
// inputs are: x, y, scalar
success := staticcall (not(0), 0x07, i, 0x60, retP, 0x40)
}
if (!success)
{
retP[0] = 0;
retP[1] = 0;
}
}
function ecInv(uint256[2] memory point) private pure
returns (uint256[2] memory invPoint)
{
invPoint[0] = point[0];
int256 n = int256(fieldSize) - int256(point[1]);
n = n % int256(fieldSize);
if (n < 0) { n += int256(fieldSize); }
invPoint[1] = uint256(n);
}
function ecAdd(uint256[2] memory p1, uint256[2] memory p2) public view
returns (uint256[2] memory retP)
{
bool success;
uint256[4] memory i = [p1[0], p1[1], p2[0], p2[1]];
assembly
{
// call ecadd precompile
// inputs are: x1, y1, x2, y2
success := staticcall (not(0), 0x06, i, 0x80, retP, 0x40)
}
if (!success)
{
retP[0] = 0;
retP[1] = 0;
}
}
function extractXYFromPoint(bytes memory data) public pure returns (uint256 x, uint256 y)
{
assembly
{
x := mload(add(data, 0x21)) //copy from 33rd byte because first 32 bytes are array length, then 1st byte of data is the 0x04;
y := mload(add(data, 0x41)) //65th byte as x value is 32 bytes.
}
}
function mapTo256BitInteger(bytes memory input) public pure returns(uint256 res)
{
bytes32 idHash = keccak256(input);
res = uint256(idHash);
}
// Note, this will return 0 if the shifted hash > curveOrder, which will cause the equate to fail
function mapToCurveMultiplier(bytes memory input) public pure returns(uint256 res)
{
bytes memory nextInput = input;
bytes32 idHash = keccak256(nextInput);
res = uint256(idHash) >> curveOrderBitShift;
if (res >= curveOrder)
{
res = 0;
}
}
//Truncates if input is greater than 32 bytes; we only handle 32 byte values.
function bytesToUint(bytes memory b) public pure returns (uint256 conv)
{
if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value
{
bytes memory b2 = new bytes(32);
uint startCopy = 0x20 + 0x20 - b.length;
assembly
{
let bcc := add(b, 0x20)
let bbc := add(b2, startCopy)
mstore(bbc, mload(bcc))
conv := mload(add(b2, 32))
}
}
else
{
assembly
{
conv := mload(add(b, 32))
}
}
}
//////////////////////////////////////////////////////////////
// DER Helper functions
//////////////////////////////////////////////////////////////
function decodeDERData(bytes memory byteCode, uint dIndex) internal pure returns(bytes memory data, uint256 index, uint256 length, bytes1 tag)
{
return decodeDERData(byteCode, dIndex, 0);
}
function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data)
{
uint256 blank = 0;
uint256 index = dIndex;
uint dStart = 0x20 + index;
uint cycles = length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank
}
data = new bytes(requiredAlloc);
assembly {
let mc := add(data, 0x20) //offset into bytes we're writing into
let cycle := 0
for
{
let cc := add(byteCode, dStart)
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(data, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back
mstore(data, length)
}
}
}
function copyStringBlock(bytes memory byteCode) internal pure returns(string memory stringData)
{
uint256 blank = 0; //blank 32 byte value
uint256 length = byteCode.length;
uint cycles = byteCode.length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - to avoid looping with single byte writes
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank, so we don't smack the next stack entry
}
stringData = new string(requiredAlloc);
//copy data in 32 byte blocks
assembly {
let cycle := 0
for
{
let mc := add(stringData, 0x20) //pointer into bytes we're writing to
let cc := add(byteCode, 0x20) //pointer to where we're reading from
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size (part of the optimisation to avoid looping adding blank bytes1)
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(stringData, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back so the returned object is the correct size
mstore(stringData, length)
}
}
}
function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) internal pure returns(bytes memory data, uint256 index, uint256 length, bytes1 tag)
{
index = dIndex;
(length, index, tag) = decodeLength(byteCode, index);
if (offset <= length)
{
uint requiredLength = length - offset;
uint dStart = index + offset;
data = copyDataBlock(byteCode, dStart, requiredLength);
}
else
{
data = bytes("");
}
index += length;
}
function decodeElement(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, bytes memory content, uint256 newIndex, bytes1 tag)
{
(content, newIndex, length, tag) = decodeDERData(byteCode, decodeIndex);
}
function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length, ) = decodeDERData(byteCode, decodeIndex, offset);
}
function decodeLength(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, uint256 newIndex, bytes1 tag)
{
uint codeLength = 1;
length = 0;
newIndex = decodeIndex;
tag = bytes1(byteCode[newIndex++]);
if ((byteCode[newIndex] & 0x80) == 0x80)
{
codeLength = uint8((byteCode[newIndex++] & 0x7f));
}
for (uint i = 0; i < codeLength; i++)
{
length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8);
}
}
function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) internal pure returns(Status memory)
{
uint length = uint8(byteCode[decodeIndex++]);
bytes32 store = 0;
for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8);
objCodes[objCodeIndex++] = uint256(store);
Status memory retVal;
retVal.decodeIndex = decodeIndex;
retVal.objCodeIndex = objCodeIndex;
return retVal;
}
struct Status {
uint decodeIndex;
uint objCodeIndex;
}
function endContract() public payable
{
if(msg.sender == owner)
{
selfdestruct(owner);
}
else revert();
}
}
|
now shrink the memory back
|
function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data)
{
uint256 blank = 0;
uint256 index = dIndex;
uint dStart = 0x20 + index;
uint cycles = length / 0x20;
uint requiredAlloc = length;
{
cycles++;
}
data = new bytes(requiredAlloc);
assembly {
let cycle := 0
for
{
let cc := add(byteCode, dStart)
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
mstore(mc, mload(cc))
}
}
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(data, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
mstore(data, length)
}
}
}
| 936,813
|
./full_match/1/0x614775d11B6209FCC12147e111a308eab684E438/sources/AlphaSorbetVault.sol
|
Transfers tokens to governance in case of emergency. Cannot be called if already finalized./
|
function emergencyWithdrawEth() external onlyGovernance {
msg.sender.transfer(address(this).balance);
}
| 2,909,710
|
/**
*Submitted for verification at Etherscan.io on 2022-04-11
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______
| || || | | || | | || | | || | | _ || || | | _ || | | | | || |
| ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___|
| | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___
| || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___|
| |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___
|_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______|
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
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: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <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/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
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));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal 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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
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 virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______
| || || | | || | | || | | || | | _ || || | | _ || | | | | || |
| ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___|
| | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___
| || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___|
| |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___
|_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______|
*/
pragma solidity ^0.7.0;
contract GeniculateBlue is ERC721, Ownable {
constructor() ERC721("Geniculate Blue", "LGN") {}
using SafeMath for uint256;
uint256 public constant nftPrice = 550000000000000000;
uint public constant MAX_PURCHASE = 11;
uint256 public constant MAX_MAIN = 475;
bool public saleIsActive = false;
uint public teamReserve = 15;
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reserve(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More.");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
teamReserve = teamReserve.sub(_reserveAmount);
}
function mint(uint _numberOfTokens) public payable {
require(saleIsActive, "Not Active.");
require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit.");
require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted.");
require(msg.value >= nftPrice, "More Ethereum.");
for(uint i = 0; i < _numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_MAIN) {
_safeMint(msg.sender, mintIndex);
}
}
}
string public mintedCode;
bool public isReconstructed = false;
mapping (uint256 => string) public geniculateSeeds;
mapping (uint256 => bool) public seedSet;
mapping (uint => string) public mintedColors;
event SeedWritten (uint256 indexed nameIndex, string newName);
function setSeed(uint256 _tokenId, string calldata currName) public {
address owner = ownerOf(_tokenId);
require(msg.sender == owner, "Incorrect.");
require(seedSet[_tokenId] == false, "Name given.");
seedSet[_tokenId] = true;
geniculateSeeds[_tokenId] = currName;
emit SeedWritten(_tokenId, currName);
}
function viewSeed(uint _tokenId) public view returns(string memory){
return geniculateSeeds[_tokenId];
}
function setCode(string calldata currName) public onlyOwner {
mintedCode = currName;
}
function viewCode() public view returns(string memory) {
return mintedCode;
}
function setColors(uint palette, string calldata palette_param) public onlyOwner {
mintedColors[palette] = palette_param;
}
function viewColors(uint palette) public view returns(string memory) {
return mintedColors[palette];
}
}
|
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;
}
| 2,048,117
|
pragma solidity 0.5.0;
import "./ERC.sol";
import "./ItemContract.sol";
contract ERC165Implementation is ERC165 {
constructor () public {
//store that contract implements ERC165
supportedInterfaces[bytes4(keccak256("supportsInterface(bytes4)"))] = true;
//Store that te contract implements ERC721
supportedInterfaces[
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes")) ^
bytes4(keccak256("safeTransferFrom(address,address,uint256")) ^
bytes4(keccak256("transferFrom(address,address,uint256")) ^
bytes4(keccak256("approve(address,uint256")) ^
bytes4(keccak256("setApprovalForAll(address,bool")) ^
bytes4(keccak256("getApproved(uint256")) ^
bytes4(keccak256("isApprovedForAll(address,address)")) ^
bytes4(keccak256("totalSupply()"))
] = true;
}
//mapping to store what interfaces are supported
mapping (bytes4 => bool) internal supportedInterfaces;
///@notice Query if a contract implements an interface.
///@param interfaceID The interface identifier, as specified in ERC-165.
///@dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise.
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return supportedInterfaces[interfaceID];
}
}
///@title ItemOwnership is the contract that implements all ERC721 standards.
/// This means that the contract takes care of all that has to do with ownerships.
///@author Håvard Pedersen, B6056952.
///@dev This will implement and make use of
/// functions, events, and storages defined in its parent-contracts.
contract ItemOwnership is ItemContract, ERC721TokenReceiver, ERC165Implementation {
address internal owner;
constructor () public {
owner = msg.sender;
}
/*** NAIVE METHODS ***/
/// @notice Count all items assigned to an owner.
/// @param _account An address for whom to query the balance.
/// @return The number of items owned by `_owner`, possibly zero.
function balanceOf(address _account) external view returns (uint) {
return users[_account].items.length;
}
/// @notice Returns a map of map. This should be accessed as follows:
/// [type][value], where type is weapon type, and value is either
/// 0 (statIncrement for stat1), 1(statIncrement for stat2),
/// 2 (Lowest roll for stat1), 3(Lowest roll for stat2).
function getStatInformation() external view returns(uint8[4][6] memory) {
return statInformation;
}
/// @notice Count items tracked by this contract.
/// @return A count of valid items tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address.
function totalSupply() external view returns (uint) {
return numberOfItems;
}
/// @notice Find the owner of an item.
/// @param _id The identifier for an item.
/// @return The address of the owner of the item.
function ownerOf(uint _id) external view returns (address) {
return ownerOfItem[_id];
}
///@dev this might seem like a redundant function, as we also have approve.
///However, this is a naive, internal call. The other approve function is external,
///and checks all parameters. This is done to lower gasprice.
///@notice does not trigger Approval event, as this will be done by the calling functions.
function _approve(address _to, uint _id) internal {
itemApprovals[_id] = _to;
}
///@dev internal function to check if address is approved for an item.
function isApprovedFor(address _user, uint _id) internal view returns (bool) {
return itemApprovals[_id] == _user;
}
///@dev check if item exists
function itemIsInGame(uint _id) internal view returns (bool) {
require(_id > 0 || _id <= ids, "Id is not valid");
require(ownerOfItem[_id] != address(0), "Item is (no longer) in the game");
return true;
}
//From AddressUtils.sol library.
///@dev check if a given address is a contract
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
///@dev check if item is on auction
///@param _id id of item to check
function isOnAuction(uint _id) internal view returns (bool) {
require(itemIsInGame(_id), "item does not exist");
User storage itemOwner = users[ownerOfItem[_id]];
return itemOwner.items[itemOwner.indexOfItem[_id]].onAuction;
}
/// @notice Handle the receipt of an NFT
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
function onERC721Received(
address,
address,
uint256,
bytes calldata
)external returns(bytes4) {
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
/*** SKEPTICAL METHODS ***/
/// @notice Change or reaffirm the approved address for an item.
/// @param _to The new approved item controller.
/// @param _id The item to approve.
function approve(address _to, uint _id) external payable {
//Make sure its a valid id
require(itemIsInGame(_id));
require(!isOnAuction(_id));
//check if caller has right to approve this item to an account
address itemOwner = ownerOfItem[_id];
require(
itemOwner == msg.sender ||
approvedForAll[owner][msg.sender],
"Must be owner or operator of the item"
);
//approve account
_approve(_to, _id);
//emit the event
emit Approval(ownerOfItem[_id], _to, _id);
}
/// @notice Get the approved address for a single item.
/// @param _id The item to find the approved address for.
/// @return The approved address for this item, or the zero address if there is none.
function getApproved(uint256 _id) external view returns (address) {
//Make sure its a valid id
require(itemIsInGame(_id), "item does not exist");
return itemApprovals[_id];
}
/// @notice Transfer ownership of an item -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING ITEMS OR ELSE
/// THEY MAY BE PERMANENTLY LOST.
/// @param _from The current owner of the item.
/// @param _to The new owner.
/// @param _id The item to transfer.
function transferFrom (
address _from,
address _to,
uint256 _id
) public payable {
address itemOwner = ownerOfItem[_id];
//Make sure its a valid id
require(itemIsInGame(_id));
//make sure item is not up for auction
require(!isOnAuction(_id));
//Check if sender is authorized to transfer item
require(
isApprovedFor(msg.sender, _id) ||
itemOwner == msg.sender ||
approvedForAll[owner][msg.sender],
"Does not have authority over that item"
);
//check if owner address matches owner parameter
require(itemOwner == _from, "The item does not belong to that account");
//call transfer function
transferOwnership(_from, _to, _id);
}
/// @notice Transfers the ownership of an item from one address to another address.
/// @param _from The current owner of the item.
/// @param _to The new owner.
/// @param _id The item to transfer.
/// @param data Additional data with no specified format, sent in call to `_to`.
function safeTransferFrom(address _from, address _to, uint256 _id, bytes calldata data) external payable {
//call transfer function to do checks and transfer item
transferFrom(_from, _to, _id);
//if caller is another contract, make sure that
//the contract has implemented ERC721, or cancel transfer
if (isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
require(
receiver.onERC721Received(msg.sender, _from, _id, data) ==
bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")),
"Contracts don't implement the same standard"
);
}
}
/// @notice Transfers the ownership of an item from one address to another address.
/// @param _from The current owner of the item.
/// @param _to The new owner.
/// @param _id The item to transfer.
function safeTransferFrom(address _from, address _to, uint256 _id) external payable {
this.safeTransferFrom(_from, _to, _id, "");
}
/// @notice Query if an address is an authorized operator for another address.
/// @param _owner The address that owns the items.
/// @param _operator The address that acts on behalf of the owner.
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise.
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets.
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operator is approved, false to revoke approval.
function setApprovalForAll(address _operator, bool _approved) external {
approvedForAll[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
///@notice This function can be used to iterate through all items of a user,
///in combination with balanceOf(_owner). This is the only way to return all
///items an address owns.
function getItemByIndex(address _owner, uint _index) public view
returns(
uint id,
uint equipmentType,
uint16 img,
uint16 stat1,
uint16 stat2,
uint8 rarity,
address ownerAddress,
bool onAuction
) {
User storage user = users[_owner];
require(user.items.length >= _index, "Owner dont have that many items.");
return getItem(_owner, _index);
}
///@notice This function can be used to iterate through all items of a user,
///in combination with balanceOf(_owner). This is the only way to return all
///items an address owns.
function getItemByID(address _owner, uint _id) public view
returns(
uint id,
uint equipmentType,
uint16 img,
uint16 stat1,
uint16 stat2,
uint8 rarity,
address ownerAddress,
bool onAuction
) {
require(itemIsInGame(_id));
require(ownerOfItem[_id] == _owner, "Thats not the owner of the item");
return getItem(_owner, users[_owner].indexOfItem[_id]);
}
///@notice function to select 3 items from a given account. This deletes the 3 items and has a chance of producing
///an item of 1 higher rarity than the previous one.
function upgrade(address _owner, uint _id1, uint _id2, uint _id3)
external {
User storage user = users[_owner];
//check that items are all owned by the given address
require(
ownerOfItem[_id1] == ownerOfItem[_id2] &&
ownerOfItem[_id1] == ownerOfItem[_id3] &&
address(ownerOfItem[_id1]) == _owner,
"All items are not owned by that address."
);
//Check that caller has authority over the account
require(
msg.sender == _owner ||
approvedForAll[_owner][msg.sender],
"You dont have the authority to do that."
);
//Check that items are not approved for trade
require(
itemApprovals[_id1] == itemApprovals[_id2] &&
itemApprovals[_id1] == itemApprovals[_id3] &&
itemApprovals[_id1] == address(0),
"Items cant be approved for trade"
);
//check that items are not up for auction
require(
!isOnAuction(_id1) &&
!isOnAuction(_id2) &&
!isOnAuction(_id3),
"Cant upgrade items that are up for auction"
);
//check that items are of same rarity
uint8 rarity = user.items[user.indexOfItem[_id1]].rarity;
require(
rarity == user.items[user.indexOfItem[_id2]].rarity &&
rarity == user.items[user.indexOfItem[_id3]].rarity,
"The items must be of same rarity"
);
//check that items are not legendary
require(
rarity != 4,
"The items must not be legendary"
);
//upgrade items
upgradeItems(_owner, _id1, _id2, _id3);
}
}
|
this might seem like a redundant function, as we also have approve.However, this is a naive, internal call. The other approve function is external,and checks all parameters. This is done to lower gasprice. does not trigger Approval event, as this will be done by the calling functions.
|
function _approve(address _to, uint _id) internal {
itemApprovals[_id] = _to;
}
| 1,805,098
|
pragma solidity 0.5.12;
pragma experimental ABIEncoderV2;
contract Token {
uint256 public totalSupply;
function BALANCEOF126(address _owner) view public returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER539(address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM134(address _from, address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function APPROVE766(address _spender, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE680(address _owner, address _spender) public view returns (uint256 remaining); //inject NONSTANDARD NAMING
event TRANSFER377(address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event APPROVAL896(address _owner, address _spender, uint256 _value); //inject NONSTANDARD NAMING
}
contract ERC20Token is Token {
function TRANSFER539(address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit TRANSFER377(msg.sender, _to, _value);
return true;
} else { return false; }
}
function TRANSFERFROM134(address _from, address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit TRANSFER377(_from, _to, _value);
return true;
} else { return false; }
}
function BALANCEOF126(address _owner) view public returns (uint256 balance) { //inject NONSTANDARD NAMING
return balances[_owner];
}
function APPROVE766(address _spender, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL896(msg.sender, _spender, _value);
return true;
}
function ALLOWANCE680(address _owner, address _spender) view public returns (uint256 remaining) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
library SafeMath {
function MUL746(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function DIV871(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function SUB288(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD535(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
assert(c >= a);
return c;
}
}
library AddressUtils {
function ISCONTRACT297(address addr) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
interface ERC165 {
function SUPPORTSINTERFACE396(bytes4 _interfaceId) //inject NONSTANDARD NAMING
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant interfaceid_erc165197 = 0x01ffc9a7; //inject NONSTANDARD NAMING
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_REGISTERINTERFACE866(interfaceid_erc165197);
}
function SUPPORTSINTERFACE396(bytes4 _interfaceId) //inject NONSTANDARD NAMING
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _REGISTERINTERFACE866(bytes4 _interfaceId) //inject NONSTANDARD NAMING
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC721Receiver {
bytes4 internal constant erc721_received613 = 0xf0b9e5ba; //inject NONSTANDARD NAMING
function ONERC721RECEIVED739( //inject NONSTANDARD NAMING
address _from,
uint256 _tokenId,
bytes memory _data
)
public
returns(bytes4);
}
contract ERC721Basic is ERC165 {
event TRANSFER377( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId
);
event APPROVAL896( //inject NONSTANDARD NAMING
address _owner,
address _approved,
uint256 _tokenId
);
event APPROVALFORALL957( //inject NONSTANDARD NAMING
address _owner,
address _operator,
bool _approved
);
function BALANCEOF126(address _owner) public view returns (uint256 _balance); //inject NONSTANDARD NAMING
function OWNEROF291(uint256 _tokenId) public view returns (address _owner); //inject NONSTANDARD NAMING
function EXISTS362(uint256 _tokenId) public view returns (bool _exists); //inject NONSTANDARD NAMING
function APPROVE766(address _to, uint256 _tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED462(uint256 _tokenId) //inject NONSTANDARD NAMING
public view returns (address _operator);
function SETAPPROVALFORALL90(address _operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL509(address _owner, address _operator) //inject NONSTANDARD NAMING
public view returns (bool);
function TRANSFERFROM134(address _from, address _to, uint256 _tokenId) public; //inject NONSTANDARD NAMING
function SAFETRANSFERFROM921(address _from, address _to, uint256 _tokenId) //inject NONSTANDARD NAMING
public;
function SAFETRANSFERFROM921( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
public;
}
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant interfaceid_erc721619 = 0x80ac58cd; //inject NONSTANDARD NAMING
bytes4 private constant interfaceid_erc721exists608 = 0x4f558e79; //inject NONSTANDARD NAMING
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant erc721_received613 = 0xf0b9e5ba; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
uint public testint;
modifier ONLYOWNEROF128(uint256 _tokenId) { //inject NONSTANDARD NAMING
require(OWNEROF291(_tokenId) == msg.sender);
_;
}
modifier CANTRANSFER884(uint256 _tokenId) { //inject NONSTANDARD NAMING
require(ISAPPROVEDOROWNER880(msg.sender, _tokenId));
_;
}
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE866(interfaceid_erc721619);
_REGISTERINTERFACE866(interfaceid_erc721exists608);
}
function BALANCEOF126(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(_owner != address(0));
return ownedTokensCount[_owner];
}
function OWNEROF291(uint256 _tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function EXISTS362(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
function APPROVE766(address _to, uint256 _tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF291(_tokenId);
require(_to != owner);
require(msg.sender == owner || ISAPPROVEDFORALL509(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit APPROVAL896(owner, _to, _tokenId);
}
function GETAPPROVED462(uint256 _tokenId) public view returns (address) { //inject NONSTANDARD NAMING
return tokenApprovals[_tokenId];
}
function SETAPPROVALFORALL90(address _to, bool _approved) public { //inject NONSTANDARD NAMING
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit APPROVALFORALL957(msg.sender, _to, _approved);
}
function ISAPPROVEDFORALL509( //inject NONSTANDARD NAMING
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
function TRANSFERFROM134( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId
)
public
CANTRANSFER884(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
CLEARAPPROVAL440(_from, _tokenId);
REMOVETOKENFROM320(_from, _tokenId);
ADDTOKENTO890(_to, _tokenId);
emit TRANSFER377(_from, _to, _tokenId);
}
function SAFETRANSFERFROM921( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId
)
public
CANTRANSFER884(_tokenId)
{
// solium-disable-next-line arg-overflow
SAFETRANSFERFROM921(_from, _to, _tokenId, "");
}
function SAFETRANSFERFROM921( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
public
CANTRANSFER884(_tokenId)
{
TRANSFERFROM134(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(CHECKANDCALLSAFETRANSFER327(_from, _to, _tokenId, _data));
}
function ISAPPROVEDOROWNER880( //inject NONSTANDARD NAMING
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = OWNEROF291(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
GETAPPROVED462(_tokenId) == _spender ||
ISAPPROVEDFORALL509(owner, _spender)
);
}
function _MINT613(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(_to != address(0));
ADDTOKENTO890(_to, _tokenId);
emit TRANSFER377(address(0), _to, _tokenId);
}
function _BURN402(address _owner, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
CLEARAPPROVAL440(_owner, _tokenId);
REMOVETOKENFROM320(_owner, _tokenId);
emit TRANSFER377(_owner, address(0), _tokenId);
}
function CLEARAPPROVAL440(address _owner, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF291(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
function ADDTOKENTO890(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].ADD535(1);
}
function REMOVETOKENFROM320(address _from, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF291(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].SUB288(1);
tokenOwner[_tokenId] = address(0);
}
function CHECKANDCALLSAFETRANSFER327( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!_to.ISCONTRACT297()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).ONERC721RECEIVED739(
_from, _tokenId, _data);
return (retval == erc721_received613);
}
}
contract ERC721BasicTokenMock is ERC721BasicToken {
function MINT436(address _to, uint256 _tokenId) public { //inject NONSTANDARD NAMING
super._MINT613(_to, _tokenId);
}
function BURN214(uint256 _tokenId) public { //inject NONSTANDARD NAMING
super._BURN402(OWNEROF291(_tokenId), _tokenId);
}
}
contract StandardBounties {
using SafeMath for uint256;
struct Bounty {
address payable[] issuers; // An array of individuals who have complete control over the bounty, and can edit any of its parameters
address[] approvers; // An array of individuals who are allowed to accept the fulfillments for a particular bounty
uint deadline; // The Unix timestamp before which all submissions must be made, and after which refunds may be processed
address token; // The address of the token associated with the bounty (should be disregarded if the tokenVersion is 0)
uint tokenVersion; // The version of the token being used for the bounty (0 for ETH, 20 for ERC20, 721 for ERC721)
uint balance; // The number of tokens which the bounty is able to pay out or refund
bool hasPaidOut; // A boolean storing whether or not the bounty has paid out at least once, meaning refunds are no longer allowed
Fulfillment[] fulfillments; // An array of Fulfillments which store the various submissions which have been made to the bounty
Contribution[] contributions; // An array of Contributions which store the contributions which have been made to the bounty
}
struct Fulfillment {
address payable[] fulfillers; // An array of addresses who should receive payouts for a given submission
address submitter; // The address of the individual who submitted the fulfillment, who is able to update the submission as needed
}
struct Contribution {
address payable contributor; // The address of the individual who contributed
uint amount; // The amount of tokens the user contributed
bool refunded; // A boolean storing whether or not the contribution has been refunded yet
}
uint public numBounties; // An integer storing the total number of bounties in the contract
mapping(uint => Bounty) public bounties; // A mapping of bountyIDs to bounties
mapping (uint => mapping (uint => bool)) public tokenBalances; // A mapping of bountyIds to tokenIds to booleans, storing whether a given bounty has a given ERC721 token in its balance
address public owner; // The address of the individual who's allowed to set the metaTxRelayer address
address public metaTxRelayer; // The address of the meta transaction relayer whose _sender is automatically trusted for all contract calls
bool public callStarted; // Ensures mutex for the entire contract
modifier CALLNOTSTARTED963(){ //inject NONSTANDARD NAMING
require(!callStarted);
callStarted = true;
_;
callStarted = false;
}
modifier VALIDATEBOUNTYARRAYINDEX962( //inject NONSTANDARD NAMING
uint _index)
{
require(_index < numBounties);
_;
}
modifier VALIDATECONTRIBUTIONARRAYINDEX279( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].contributions.length);
_;
}
modifier VALIDATEFULFILLMENTARRAYINDEX396( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].fulfillments.length);
_;
}
modifier VALIDATEISSUERARRAYINDEX737( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].issuers.length);
_;
}
modifier VALIDATEAPPROVERARRAYINDEX32( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].approvers.length);
_;
}
modifier ONLYISSUER653( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId)
{
require(_sender == bounties[_bountyId].issuers[_issuerId]);
_;
}
modifier ONLYSUBMITTER83( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _fulfillmentId)
{
require(_sender ==
bounties[_bountyId].fulfillments[_fulfillmentId].submitter);
_;
}
modifier ONLYCONTRIBUTOR9( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _contributionId)
{
require(_sender ==
bounties[_bountyId].contributions[_contributionId].contributor);
_;
}
modifier ISAPPROVER33( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _approverId)
{
require(_sender == bounties[_bountyId].approvers[_approverId]);
_;
}
modifier HASNOTPAID405( //inject NONSTANDARD NAMING
uint _bountyId)
{
require(!bounties[_bountyId].hasPaidOut);
_;
}
modifier HASNOTREFUNDED93( //inject NONSTANDARD NAMING
uint _bountyId,
uint _contributionId)
{
require(!bounties[_bountyId].contributions[_contributionId].refunded);
_;
}
modifier SENDERISVALID782( //inject NONSTANDARD NAMING
address _sender)
{
require(msg.sender == _sender || msg.sender == metaTxRelayer);
_;
}
constructor() public {
// The owner of the contract is automatically designated to be the deployer of the contract
owner = msg.sender;
}
function SETMETATXRELAYER306(address _relayer) //inject NONSTANDARD NAMING
external
{
require(msg.sender == owner); // Checks that only the owner can call
require(metaTxRelayer == address(0)); // Ensures the meta tx relayer can only be set once
metaTxRelayer = _relayer;
}
function ISSUEBOUNTY607( //inject NONSTANDARD NAMING
address payable _sender,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion)
public
SENDERISVALID782(_sender)
returns (uint)
{
require(_tokenVersion == 0 || _tokenVersion == 20 || _tokenVersion == 721); // Ensures a bounty can only be issued with a valid token version
require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
uint bountyId = numBounties; // The next bounty's index will always equal the number of existing bounties
Bounty storage newBounty = bounties[bountyId];
newBounty.issuers = _issuers;
newBounty.approvers = _approvers;
newBounty.deadline = _deadline;
newBounty.tokenVersion = _tokenVersion;
if (_tokenVersion != 0){
newBounty.token = _token;
}
numBounties = numBounties.ADD535(1); // Increments the number of bounties, since a new one has just been added
emit BOUNTYISSUED291(bountyId,
_sender,
_issuers,
_approvers,
_data, // Instead of storing the string on-chain, it is emitted within the event for easy off-chain consumption
_deadline,
_token,
_tokenVersion);
return (bountyId);
}
function ISSUEANDCONTRIBUTE529( //inject NONSTANDARD NAMING
address payable _sender,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion,
uint _depositAmount)
public
payable
returns(uint)
{
uint bountyId = ISSUEBOUNTY607(_sender, _issuers, _approvers, _data, _deadline, _token, _tokenVersion);
CONTRIBUTE618(_sender, bountyId, _depositAmount);
return (bountyId);
}
function CONTRIBUTE618( //inject NONSTANDARD NAMING
address payable _sender,
uint _bountyId,
uint _amount)
public
payable
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
CALLNOTSTARTED963
{
require(_amount > 0); // Contributions of 0 tokens or token ID 0 should fail
bounties[_bountyId].contributions.push(
Contribution(_sender, _amount, false)); // Adds the contribution to the bounty
if (bounties[_bountyId].tokenVersion == 0){
bounties[_bountyId].balance = bounties[_bountyId].balance.ADD535(_amount); // Increments the balance of the bounty
require(msg.value == _amount);
} else if (bounties[_bountyId].tokenVersion == 20){
bounties[_bountyId].balance = bounties[_bountyId].balance.ADD535(_amount); // Increments the balance of the bounty
require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds
require(ERC20Token(bounties[_bountyId].token).TRANSFERFROM134(_sender,
address(this),
_amount));
} else if (bounties[_bountyId].tokenVersion == 721){
tokenBalances[_bountyId][_amount] = true; // Adds the 721 token to the balance of the bounty
require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds
ERC721BasicToken(bounties[_bountyId].token).TRANSFERFROM134(_sender,
address(this),
_amount);
} else {
revert();
}
emit CONTRIBUTIONADDED888(_bountyId,
bounties[_bountyId].contributions.length - 1, // The new contributionId
_sender,
_amount);
}
function REFUNDCONTRIBUTION719( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _contributionId)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATECONTRIBUTIONARRAYINDEX279(_bountyId, _contributionId)
ONLYCONTRIBUTOR9(_sender, _bountyId, _contributionId)
HASNOTPAID405(_bountyId)
HASNOTREFUNDED93(_bountyId, _contributionId)
CALLNOTSTARTED963
{
require(now > bounties[_bountyId].deadline); // Refunds may only be processed after the deadline has elapsed
Contribution storage contribution = bounties[_bountyId].contributions[_contributionId];
contribution.refunded = true;
TRANSFERTOKENS903(_bountyId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor
emit CONTRIBUTIONREFUNDED423(_bountyId, _contributionId);
}
function REFUNDMYCONTRIBUTIONS1000( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint[] memory _contributionIds)
public
SENDERISVALID782(_sender)
{
for (uint i = 0; i < _contributionIds.length; i++){
REFUNDCONTRIBUTION719(_sender, _bountyId, _contributionIds[i]);
}
}
function REFUNDCONTRIBUTIONS786( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint[] memory _contributionIds)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
CALLNOTSTARTED963
{
for (uint i = 0; i < _contributionIds.length; i++){
require(_contributionIds[i] < bounties[_bountyId].contributions.length);
Contribution storage contribution = bounties[_bountyId].contributions[_contributionIds[i]];
require(!contribution.refunded);
contribution.refunded = true;
TRANSFERTOKENS903(_bountyId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor
}
emit CONTRIBUTIONSREFUNDED218(_bountyId, _sender, _contributionIds);
}
function DRAINBOUNTY345( //inject NONSTANDARD NAMING
address payable _sender,
uint _bountyId,
uint _issuerId,
uint[] memory _amounts)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
CALLNOTSTARTED963
{
if (bounties[_bountyId].tokenVersion == 0 || bounties[_bountyId].tokenVersion == 20){
require(_amounts.length == 1); // ensures there's only 1 amount of tokens to be returned
require(_amounts[0] <= bounties[_bountyId].balance); // ensures an issuer doesn't try to drain the bounty of more tokens than their balance permits
TRANSFERTOKENS903(_bountyId, _sender, _amounts[0]); // Performs the draining of tokens to the issuer
} else {
for (uint i = 0; i < _amounts.length; i++){
require(tokenBalances[_bountyId][_amounts[i]]);// ensures an issuer doesn't try to drain the bounty of a token it doesn't have in its balance
TRANSFERTOKENS903(_bountyId, _sender, _amounts[i]);
}
}
emit BOUNTYDRAINED424(_bountyId, _sender, _amounts);
}
function PERFORMACTION966( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
{
emit ACTIONPERFORMED922(_bountyId, _sender, _data); // The _data string is emitted in an event for easy off-chain consumption
}
function FULFILLBOUNTY596( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
{
require(now < bounties[_bountyId].deadline); // Submissions are only allowed to be made before the deadline
require(_fulfillers.length > 0); // Submissions with no fulfillers would mean no one gets paid out
bounties[_bountyId].fulfillments.push(Fulfillment(_fulfillers, _sender));
emit BOUNTYFULFILLED198(_bountyId,
(bounties[_bountyId].fulfillments.length - 1),
_fulfillers,
_data, // The _data string is emitted in an event for easy off-chain consumption
_sender);
}
function UPDATEFULFILLMENT168( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _fulfillmentId,
address payable[] memory _fulfillers,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEFULFILLMENTARRAYINDEX396(_bountyId, _fulfillmentId)
ONLYSUBMITTER83(_sender, _bountyId, _fulfillmentId) // Only the original submitter of a fulfillment may update their submission
{
bounties[_bountyId].fulfillments[_fulfillmentId].fulfillers = _fulfillers;
emit FULFILLMENTUPDATED42(_bountyId,
_fulfillmentId,
_fulfillers,
_data); // The _data string is emitted in an event for easy off-chain consumption
}
function ACCEPTFULFILLMENT330( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _fulfillmentId,
uint _approverId,
uint[] memory _tokenAmounts)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEFULFILLMENTARRAYINDEX396(_bountyId, _fulfillmentId)
ISAPPROVER33(_sender, _bountyId, _approverId)
CALLNOTSTARTED963
{
// now that the bounty has paid out at least once, refunds are no longer possible
bounties[_bountyId].hasPaidOut = true;
Fulfillment storage fulfillment = bounties[_bountyId].fulfillments[_fulfillmentId];
require(_tokenAmounts.length == fulfillment.fulfillers.length); // Each fulfiller should get paid some amount of tokens (this can be 0)
for (uint256 i = 0; i < fulfillment.fulfillers.length; i++){
if (_tokenAmounts[i] > 0){
// for each fulfiller associated with the submission
TRANSFERTOKENS903(_bountyId, fulfillment.fulfillers[i], _tokenAmounts[i]);
}
}
emit FULFILLMENTACCEPTED617(_bountyId,
_fulfillmentId,
_sender,
_tokenAmounts);
}
function FULFILLANDACCEPT822( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data,
uint _approverId,
uint[] memory _tokenAmounts)
public
SENDERISVALID782(_sender)
{
// first fulfills the bounty on behalf of the fulfillers
FULFILLBOUNTY596(_sender, _bountyId, _fulfillers, _data);
// then accepts the fulfillment
ACCEPTFULFILLMENT330(_sender,
_bountyId,
bounties[_bountyId].fulfillments.length - 1,
_approverId,
_tokenAmounts);
}
function CHANGEBOUNTY775( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers,
address payable[] memory _approvers,
string memory _data,
uint _deadline)
public
SENDERISVALID782(_sender)
{
require(_bountyId < numBounties); // makes the validateBountyArrayIndex modifier in-line to avoid stack too deep errors
require(_issuerId < bounties[_bountyId].issuers.length); // makes the validateIssuerArrayIndex modifier in-line to avoid stack too deep errors
require(_sender == bounties[_bountyId].issuers[_issuerId]); // makes the onlyIssuer modifier in-line to avoid stack too deep errors
require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
bounties[_bountyId].issuers = _issuers;
bounties[_bountyId].approvers = _approvers;
bounties[_bountyId].deadline = _deadline;
emit BOUNTYCHANGED890(_bountyId,
_sender,
_issuers,
_approvers,
_data,
_deadline);
}
function CHANGEISSUER877( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _issuerIdToChange,
address payable _newIssuer)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerIdToChange)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
require(_issuerId < bounties[_bountyId].issuers.length || _issuerId == 0);
bounties[_bountyId].issuers[_issuerIdToChange] = _newIssuer;
emit BOUNTYISSUERSUPDATED404(_bountyId, _sender, bounties[_bountyId].issuers);
}
function CHANGEAPPROVER313( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _approverId,
address payable _approver)
external
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
VALIDATEAPPROVERARRAYINDEX32(_bountyId, _approverId)
{
bounties[_bountyId].approvers[_approverId] = _approver;
emit BOUNTYAPPROVERSUPDATED564(_bountyId, _sender, bounties[_bountyId].approvers);
}
function CHANGEISSUERANDAPPROVER5( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _issuerIdToChange,
uint _approverIdToChange,
address payable _issuer)
external
SENDERISVALID782(_sender)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
require(_bountyId < numBounties);
require(_approverIdToChange < bounties[_bountyId].approvers.length);
require(_issuerIdToChange < bounties[_bountyId].issuers.length);
bounties[_bountyId].issuers[_issuerIdToChange] = _issuer;
bounties[_bountyId].approvers[_approverIdToChange] = _issuer;
emit BOUNTYISSUERSUPDATED404(_bountyId, _sender, bounties[_bountyId].issuers);
emit BOUNTYAPPROVERSUPDATED564(_bountyId, _sender, bounties[_bountyId].approvers);
}
function CHANGEDATA475( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
emit BOUNTYDATACHANGED202(_bountyId, _sender, _data); // The new _data is emitted within an event rather than being stored on-chain for minimized gas costs
}
function CHANGEDEADLINE144( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _deadline)
external
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
bounties[_bountyId].deadline = _deadline;
emit BOUNTYDEADLINECHANGED293(_bountyId, _sender, _deadline);
}
function ADDISSUERS127( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
for (uint i = 0; i < _issuers.length; i++){
bounties[_bountyId].issuers.push(_issuers[i]);
}
emit BOUNTYISSUERSUPDATED404(_bountyId, _sender, bounties[_bountyId].issuers);
}
function ADDAPPROVERS15( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
address[] memory _approvers)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
for (uint i = 0; i < _approvers.length; i++){
bounties[_bountyId].approvers.push(_approvers[i]);
}
emit BOUNTYAPPROVERSUPDATED564(_bountyId, _sender, bounties[_bountyId].approvers);
}
function GETBOUNTY268(uint _bountyId) //inject NONSTANDARD NAMING
external
view
returns (Bounty memory)
{
return bounties[_bountyId];
}
function TRANSFERTOKENS903(uint _bountyId, address payable _to, uint _amount) //inject NONSTANDARD NAMING
internal
{
if (bounties[_bountyId].tokenVersion == 0){
require(_amount > 0); // Sending 0 tokens should throw
require(bounties[_bountyId].balance >= _amount);
bounties[_bountyId].balance = bounties[_bountyId].balance.SUB288(_amount);
_to.transfer(_amount);
} else if (bounties[_bountyId].tokenVersion == 20){
require(_amount > 0); // Sending 0 tokens should throw
require(bounties[_bountyId].balance >= _amount);
bounties[_bountyId].balance = bounties[_bountyId].balance.SUB288(_amount);
require(ERC20Token(bounties[_bountyId].token).TRANSFER539(_to, _amount));
} else if (bounties[_bountyId].tokenVersion == 721){
require(tokenBalances[_bountyId][_amount]);
tokenBalances[_bountyId][_amount] = false; // Removes the 721 token from the balance of the bounty
ERC721BasicToken(bounties[_bountyId].token).TRANSFERFROM134(address(this),
_to,
_amount);
} else {
revert();
}
}
event BOUNTYISSUED291(uint _bountyId, address payable _creator, address payable[] _issuers, address[] _approvers, string _data, uint _deadline, address _token, uint _tokenVersion); //inject NONSTANDARD NAMING
event CONTRIBUTIONADDED888(uint _bountyId, uint _contributionId, address payable _contributor, uint _amount); //inject NONSTANDARD NAMING
event CONTRIBUTIONREFUNDED423(uint _bountyId, uint _contributionId); //inject NONSTANDARD NAMING
event CONTRIBUTIONSREFUNDED218(uint _bountyId, address _issuer, uint[] _contributionIds); //inject NONSTANDARD NAMING
event BOUNTYDRAINED424(uint _bountyId, address _issuer, uint[] _amounts); //inject NONSTANDARD NAMING
event ACTIONPERFORMED922(uint _bountyId, address _fulfiller, string _data); //inject NONSTANDARD NAMING
event BOUNTYFULFILLED198(uint _bountyId, uint _fulfillmentId, address payable[] _fulfillers, string _data, address _submitter); //inject NONSTANDARD NAMING
event FULFILLMENTUPDATED42(uint _bountyId, uint _fulfillmentId, address payable[] _fulfillers, string _data); //inject NONSTANDARD NAMING
event FULFILLMENTACCEPTED617(uint _bountyId, uint _fulfillmentId, address _approver, uint[] _tokenAmounts); //inject NONSTANDARD NAMING
event BOUNTYCHANGED890(uint _bountyId, address _changer, address payable[] _issuers, address payable[] _approvers, string _data, uint _deadline); //inject NONSTANDARD NAMING
event BOUNTYISSUERSUPDATED404(uint _bountyId, address _changer, address payable[] _issuers); //inject NONSTANDARD NAMING
event BOUNTYAPPROVERSUPDATED564(uint _bountyId, address _changer, address[] _approvers); //inject NONSTANDARD NAMING
event BOUNTYDATACHANGED202(uint _bountyId, address _changer, string _data); //inject NONSTANDARD NAMING
event BOUNTYDEADLINECHANGED293(uint _bountyId, address _changer, uint _deadline); //inject NONSTANDARD NAMING
}
contract BountiesMetaTxRelayer {
// This contract serves as a relayer for meta txns being sent to the Bounties contract
StandardBounties public bountiesContract;
mapping(address => uint) public replayNonce;
constructor(address _contract) public {
bountiesContract = StandardBounties(_contract);
}
function METAISSUEBOUNTY189( //inject NONSTANDARD NAMING
bytes memory signature,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion,
uint _nonce)
public
returns (uint)
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaIssueBounty",
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_nonce));
address signer = GETSIGNER512(metaHash, signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
return bountiesContract.ISSUEBOUNTY607(address(uint160(signer)),
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion);
}
function METAISSUEANDCONTRIBUTE154( //inject NONSTANDARD NAMING
bytes memory signature,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion,
uint _depositAmount,
uint _nonce)
public
payable
returns (uint)
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaIssueAndContribute",
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_depositAmount,
_nonce));
address signer = GETSIGNER512(metaHash, signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
if (msg.value > 0){
return bountiesContract.ISSUEANDCONTRIBUTE529.value(msg.value)(address(uint160(signer)),
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_depositAmount);
} else {
return bountiesContract.ISSUEANDCONTRIBUTE529(address(uint160(signer)),
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_depositAmount);
}
}
function METACONTRIBUTE650( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _amount,
uint _nonce)
public
payable
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaContribute",
_bountyId,
_amount,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
if (msg.value > 0){
bountiesContract.CONTRIBUTE618.value(msg.value)(address(uint160(signer)), _bountyId, _amount);
} else {
bountiesContract.CONTRIBUTE618(address(uint160(signer)), _bountyId, _amount);
}
}
function METAREFUNDCONTRIBUTION168( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _contributionId,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundContribution",
_bountyId,
_contributionId,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.REFUNDCONTRIBUTION719(signer, _bountyId, _contributionId);
}
function METAREFUNDMYCONTRIBUTIONS651( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint[] memory _contributionIds,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundMyContributions",
_bountyId,
_contributionIds,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.REFUNDMYCONTRIBUTIONS1000(signer, _bountyId, _contributionIds);
}
function METAREFUNDCONTRIBUTIONS334( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint[] memory _contributionIds,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundContributions",
_bountyId,
_issuerId,
_contributionIds,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.REFUNDCONTRIBUTIONS786(signer, _bountyId, _issuerId, _contributionIds);
}
function METADRAINBOUNTY623( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint[] memory _amounts,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaDrainBounty",
_bountyId,
_issuerId,
_amounts,
_nonce));
address payable signer = address(uint160(GETSIGNER512(metaHash, _signature)));
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.DRAINBOUNTY345(signer, _bountyId, _issuerId, _amounts);
}
function METAPERFORMACTION278( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaPerformAction",
_bountyId,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.PERFORMACTION966(signer, _bountyId, _data);
}
function METAFULFILLBOUNTY952( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaFulfillBounty",
_bountyId,
_fulfillers,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.FULFILLBOUNTY596(signer, _bountyId, _fulfillers, _data);
}
function METAUPDATEFULFILLMENT854( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _fulfillmentId,
address payable[] memory _fulfillers,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaUpdateFulfillment",
_bountyId,
_fulfillmentId,
_fulfillers,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.UPDATEFULFILLMENT168(signer, _bountyId, _fulfillmentId, _fulfillers, _data);
}
function METAACCEPTFULFILLMENT218( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _fulfillmentId,
uint _approverId,
uint[] memory _tokenAmounts,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaAcceptFulfillment",
_bountyId,
_fulfillmentId,
_approverId,
_tokenAmounts,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.ACCEPTFULFILLMENT330(signer,
_bountyId,
_fulfillmentId,
_approverId,
_tokenAmounts);
}
function METAFULFILLANDACCEPT21( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data,
uint _approverId,
uint[] memory _tokenAmounts,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaFulfillAndAccept",
_bountyId,
_fulfillers,
_data,
_approverId,
_tokenAmounts,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.FULFILLANDACCEPT822(signer,
_bountyId,
_fulfillers,
_data,
_approverId,
_tokenAmounts);
}
function METACHANGEBOUNTY750( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers,
address payable[] memory _approvers,
string memory _data,
uint _deadline,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeBounty",
_bountyId,
_issuerId,
_issuers,
_approvers,
_data,
_deadline,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEBOUNTY775(signer,
_bountyId,
_issuerId,
_issuers,
_approvers,
_data,
_deadline);
}
function METACHANGEISSUER928( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint _issuerIdToChange,
address payable _newIssuer,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeIssuer",
_bountyId,
_issuerId,
_issuerIdToChange,
_newIssuer,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEISSUER877(signer,
_bountyId,
_issuerId,
_issuerIdToChange,
_newIssuer);
}
function METACHANGEAPPROVER522( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint _approverId,
address payable _approver,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeApprover",
_bountyId,
_issuerId,
_approverId,
_approver,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEAPPROVER313(signer,
_bountyId,
_issuerId,
_approverId,
_approver);
}
function METACHANGEDATA703( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeData",
_bountyId,
_issuerId,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEDATA475(signer,
_bountyId,
_issuerId,
_data);
}
function METACHANGEDEADLINE27( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint _deadline,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeDeadline",
_bountyId,
_issuerId,
_deadline,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEDEADLINE144(signer,
_bountyId,
_issuerId,
_deadline);
}
function METAADDISSUERS741( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaAddIssuers",
_bountyId,
_issuerId,
_issuers,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.ADDISSUERS127(signer,
_bountyId,
_issuerId,
_issuers);
}
function METAADDAPPROVERS523( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
address[] memory _approvers,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaAddApprovers",
_bountyId,
_issuerId,
_approvers,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.ADDAPPROVERS15(signer,
_bountyId,
_issuerId,
_approvers);
}
function GETSIGNER512( //inject NONSTANDARD NAMING
bytes32 _hash,
bytes memory _signature)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
if (_signature.length != 65){
return address(0);
}
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
if (v < 27){
v += 27;
}
if (v != 27 && v != 28){
return address(0);
} else {
return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), v, r, s );
}
}
}
|
inject NONSTANDARD NAMING
|
function SETAPPROVALFORALL90(address _operator, bool _approved) public;
| 12,856,798
|
./full_match/1/0xfAe57b0101D3e1B52d31C0449454049CF3E80793/sources/contracts/AquarelleBioGenerativeAssets.sol
|
funtion to get all _owner nft tokens id /
|
function getTokenIds(address _owner) public view returns (uint[] memory) {
uint[] memory _tokensOfOwner = new uint[](ERC721.balanceOf(_owner));
uint i;
for (i=0;i<ERC721.balanceOf(_owner);i++){
_tokensOfOwner[i] = ERC721Enumerable.tokenOfOwnerByIndex(_owner, i);
}
return (_tokensOfOwner);
}
| 17,196,713
|
./full_match/43113/0xF97FA6A8b0407deddE2336eA98Bc688b34901c52/sources/project_/contracts/Twenty6Fifty2.sol
|
set the address for the $fold smart contract _address contract address/
|
function setFoldStaking(address _address) external onlyOwner notLocked {
foldStaking = IFoldStaking(_address);
}
| 7,209,127
|
./full_match/1/0xbf5A7F3629fB325E2a8453D595AB103465F75E62/sources/src/portals/router/RouterBase.sol
|
Permit function for gasless approvals. Supports both EIP-2612 and DAI style permits with split signatures, as well as Yearn like permits with combined signatures owner The address which is a source of funds and has signed the Permit token The address of the token to permit permitPayload The permit payload containing the permit parameters See IPermit.sol for more details
|
function _permit(
address owner,
address token,
IPortalsRouter.PermitPayload calldata permitPayload
) internal {
if (permitPayload.splitSignature) {
bytes memory signature = permitPayload.signature;
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (permitPayload.daiPermit) {
IPermit(token).permit(
owner,
address(this),
ERC20(token).nonces(owner),
permitPayload.deadline,
true,
v,
r,
s
);
IPermit(token).permit(
owner,
address(this),
permitPayload.amount,
permitPayload.deadline,
v,
r,
s
);
}
IPermit(token).permit(
owner,
address(this),
permitPayload.amount,
permitPayload.deadline,
permitPayload.signature
);
}
}
| 9,619,754
|
pragma solidity ^0.4.13;
// **-----------------------------------------------
// 0.4.13+commit.0fb4cb1a
// [Assistive Reality ARX ERC20 token & crowdsale contract w/10% dev alloc]
// [https://aronline.io/icoinfo]
// [v3.2 final released 10/09/17 final masterARXsale32mainnet.sol]
// [Adapted from Ethereum standard crowdsale contract]
// [Contact staff@aronline.io for any queries]
// [Join us in changing the world]
// [aronline.io]
// **-----------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
// -------------------------------------------------
// Security reviews completed 10/09/17 [passed OK]
// Functional reviews completed 10/09/17 [passed OK]
// Final code revision and regression test cycle complete 10/09/17 [passed]
// https://github.com/assistivereality/ico/blob/master/3.2crowdsaletestsARXmainnet.txt
// -------------------------------------------------
contract owned { // security reviewed 10/09/17
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract SafeMath { // security reviewed 10/09/17
function safeMul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
safeAssert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal returns (uint256) {
safeAssert(b > 0);
uint256 c = a / b;
safeAssert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
safeAssert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
safeAssert(c>=a && c>=b);
return c;
}
function safeAssert(bool assertion) internal {
if (!assertion) revert();
}
}
contract ERC20Interface is owned, SafeMath { // security reviewed 10/09/17
function totalSupply() constant returns (uint256 tokenTotalSupply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Buy(address indexed _sender, uint256 _eth, uint256 _ARX);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address _from, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Refund(address indexed _refunder, uint256 _value);
}
contract ARXCrowdsale is ERC20Interface { // security reviewed 10/09/17
// deployment variables for dynamic supply token
string public constant standard = "ARX";
string public constant name = "Assistive Reality";
string public constant symbol = "ARX";
uint8 public constant decimals = 18;
uint256 _totalSupply = 0;
// multi-sig addresses and price variable
address public admin = owner; // admin address
address public beneficiaryMultiSig; // beneficiaryMultiSig (founder group) multi-sig wallet account
address public foundationFundMultisig; // foundationFundMultisig multi-sig wallet address - Assistive Reality foundation fund
uint256 public tokensPerEthPrice; // priceVar e.g. 2,000 tokens per Eth
// uint256 values for min,max,caps,tracking
uint256 public amountRaisedInWei; // total amount raised in Wei e.g. 21 000 000 000 000 000 000 = 21 Eth
uint256 public fundingMaxInWei; // funding max in Wei e.g. 21 000 000 000 000 000 000 = 21 Eth
uint256 public fundingMinInWei; // funding min in Wei e.g. 11 000 000 000 000 000 000 = 11 Eth
uint256 public fundingMaxInEth; // funding max in Eth (approx) e.g. 21 Eth
uint256 public fundingMinInEth; // funding min in Eth (approx) e.g. 11 Eth
uint256 public remainingCapInWei; // amount of cap remaining to raise in Wei e.g. 1 200 000 000 000 000 000 = 1.2 Eth remaining
uint256 public remainingCapInEth; // amount of cap remaining to raise in Eth (approx) e.g. 1
uint256 public foundationFundTokenCountInWei; // 10% additional tokens generated and sent to foundationFundMultisig/Assistive Reality foundation, 18 decimals
// loop control, ICO startup and limiters
string public CurrentStatus = ""; // current crowdsale status
uint256 public fundingStartBlock; // crowdsale start block#
uint256 public fundingEndBlock; // crowdsale end block#
bool public isCrowdSaleFinished = false; // boolean for crowdsale completed or not
bool public isCrowdSaleSetup = false; // boolean for crowdsale setup
bool public halted = false; // boolean for halted or not
bool public founderTokensAvailable = false; // variable to set false after generating founderTokens
// balance mapping and transfer allowance array
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
event Buy(address indexed _sender, uint256 _eth, uint256 _ARX);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address _from, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Refund(address indexed _refunder, uint256 _value);
// default function, map admin
function ARXCrowdsale() onlyOwner {
admin = msg.sender;
CurrentStatus = "Crowdsale deployed to chain";
}
// total number of tokens issued so far, normalised
function totalSupply() constant returns (uint256 tokenTotalSupply) {
tokenTotalSupply = safeDiv(_totalSupply,1 ether);
}
// get the account balance
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// returns crowdsale max funding in Eth, low res
function fundingMaxInEth() constant returns (uint256 fundingMaximumInEth) {
fundingMaximumInEth = safeDiv(fundingMaxInWei,1 ether);
}
// returns crowdsale min funding in Eth, low res
function fundingMinInEth() constant returns (uint256 fundingMinimumInEth) {
fundingMinimumInEth = safeDiv(fundingMinInWei,1 ether);
}
// returns crowdsale progress (funds raised) in Eth, low res
function amountRaisedInEth() constant returns (uint256 amountRaisedSoFarInEth) {
amountRaisedSoFarInEth = safeDiv(amountRaisedInWei,1 ether);
}
// returns crowdsale remaining cap (hardcap) in Eth, low res
function remainingCapInEth() constant returns (uint256 remainingHardCapInEth) {
remainingHardCapInEth = safeDiv(remainingCapInWei,1 ether);
}
// ERC20 token transfer function
function transfer(address _to, uint256 _amount) returns (bool success) {
require(!(_to == 0x0));
if ((balances[msg.sender] >= _amount)
&& (_amount > 0)
&& ((safeAdd(balances[_to],_amount) > balances[_to]))) {
balances[msg.sender] = safeSub(balances[msg.sender], _amount);
balances[_to] = safeAdd(balances[_to], _amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// ERC20 token transferFrom function
function transferFrom(
address _from,
address _to,
uint256 _amount) returns (bool success) {
require(!(_to == 0x0));
if ((balances[_from] >= _amount)
&& (allowed[_from][msg.sender] >= _amount)
&& (_amount > 0)
&& (safeAdd(balances[_to],_amount) > balances[_to])) {
balances[_from] = safeSub(balances[_from], _amount);
allowed[_from][msg.sender] = safeSub((allowed[_from][msg.sender]),_amount);
balances[_to] = safeAdd(balances[_to], _amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// ERC20 allow _spender to withdraw, multiple times, up to the _value amount
function approve(address _spender, uint256 _amount) returns (bool success) {
//Fix for known double-spend https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit#
//Input must either set allow amount to 0, or have 0 already set, to workaround issue
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// ERC20 return allowance for given owner spender pair
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// setup the CrowdSale parameters
function SetupCrowdsale(uint256 _fundingStartBlock, uint256 _fundingEndBlock) onlyOwner returns (bytes32 response) {
if ((msg.sender == admin)
&& (!(isCrowdSaleSetup))
&& (!(beneficiaryMultiSig > 0))
&& (!(fundingMaxInWei > 0))) {
// mainnet values
beneficiaryMultiSig = 0xd93333f8cb765397A5D0d0e0ba53A2899B48511f;
foundationFundMultisig = 0x70A0bE1a5d8A9F39afED536Ec7b55d87067371aA;
// mainnet funding targets with 18 decimals
fundingMaxInWei = 70000000000000000000000; //70 000 000 000 000 000 000 000 = 70,000 Eth (hard cap) - crowdsale no longer accepts Eth after this value
fundingMinInWei = 3500000000000000000000; //3 500 000 000 000 000 000 000 = 3,500 Eth (soft cap) - crowdsale is considered success after this value
// value of ARX token for mainnet. if hardcap is reached, this results in 280,000,000 ARX tokens in general supply (+28,000,000 in the foundationFundMultisig for a total supply of 308,000,000)
tokensPerEthPrice = 4000; // 4,000 tokens per Eth
// update values
fundingMaxInEth = safeDiv(fundingMaxInWei,1 ether); //approximate to 1 Eth due to resolution, provided for ease/viewing only
fundingMinInEth = safeDiv(fundingMinInWei,1 ether); //approximate to 1 Eth due to resolution, provided for ease/viewing only
remainingCapInWei = fundingMaxInWei;
remainingCapInEth = safeDiv(remainingCapInWei,1 ether); //approximate to 1 Eth due to resolution, provided for ease/viewing only
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
// configure crowdsale
isCrowdSaleSetup = true;
CurrentStatus = "Crowdsale is setup";
return "Crowdsale is setup";
} else if (msg.sender != admin) {
return "not authorized";
} else {
return "campaign cannot be changed";
}
}
// default payable function when sending ether to this contract
function () payable {
require(msg.data.length == 0);
BuyTokens();
}
function BuyTokens() payable {
// 0. conditions (length, crowdsale setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc)
require((!(msg.value == 0))
&& (!(halted))
&& (isCrowdSaleSetup)
&& (!((safeAdd(amountRaisedInWei,msg.value)) > fundingMaxInWei))
&& (block.number >= fundingStartBlock)
&& (block.number <= fundingEndBlock)
&& (!(isCrowdSaleFinished)));
// 1. vars
address recipient = msg.sender; // to simplify refunding
uint256 amount = msg.value;
uint256 rewardTransferAmount = 0;
// 2. effects
amountRaisedInWei = safeAdd(amountRaisedInWei,amount);
remainingCapInWei = safeSub(fundingMaxInWei,amountRaisedInWei);
rewardTransferAmount = safeMul(amount,tokensPerEthPrice);
// 3. interaction
balances[recipient] = safeAdd(balances[recipient], rewardTransferAmount);
_totalSupply = safeAdd(_totalSupply, rewardTransferAmount);
Transfer(this, recipient, rewardTransferAmount);
Buy(recipient, amount, rewardTransferAmount);
}
function AllocateFounderTokens() onlyOwner {
require(isCrowdSaleFinished && founderTokensAvailable && (foundationFundTokenCountInWei == 0));
// calculate additional 10% tokens to allocate for foundation developer distributions
foundationFundTokenCountInWei = safeMul((safeDiv(amountRaisedInWei,10)), tokensPerEthPrice);
// generate and send foundation developer token distributions
balances[foundationFundMultisig] = safeAdd(balances[foundationFundMultisig], foundationFundTokenCountInWei);
_totalSupply = safeAdd(_totalSupply, foundationFundTokenCountInWei);
Transfer(this, foundationFundMultisig, foundationFundTokenCountInWei);
Buy(foundationFundMultisig, 0, foundationFundTokenCountInWei);
founderTokensAvailable = false;
}
function beneficiaryMultiSigWithdraw(uint256 _amount) onlyOwner {
require(isCrowdSaleFinished && (amountRaisedInWei >= fundingMinInWei));
beneficiaryMultiSig.transfer(_amount);
}
function checkGoalReached() onlyOwner returns (bytes32 response) { // return crowdfund status to owner for each result case, update public constant
require (!(halted) && isCrowdSaleSetup);
if ((amountRaisedInWei < fundingMinInWei) && (block.number <= fundingEndBlock && block.number >= fundingStartBlock)) { // ICO in progress, under softcap
founderTokensAvailable = false;
isCrowdSaleFinished = false;
CurrentStatus = "In progress (Eth < Softcap)";
return "In progress (Eth < Softcap)";
} else if ((amountRaisedInWei < fundingMinInWei) && (block.number < fundingStartBlock)) { // ICO has not started
founderTokensAvailable = false;
isCrowdSaleFinished = false;
CurrentStatus = "Crowdsale is setup";
return "Crowdsale is setup";
} else if ((amountRaisedInWei < fundingMinInWei) && (block.number > fundingEndBlock)) { // ICO ended, under softcap
founderTokensAvailable = false;
isCrowdSaleFinished = true;
CurrentStatus = "Unsuccessful (Eth < Softcap)";
return "Unsuccessful (Eth < Softcap)";
} else if ((amountRaisedInWei >= fundingMinInWei) && (amountRaisedInWei >= fundingMaxInWei)) { // ICO ended, at hardcap!
if (foundationFundTokenCountInWei == 0) {
founderTokensAvailable = true;
isCrowdSaleFinished = true;
CurrentStatus = "Successful (Eth >= Hardcap)!";
return "Successful (Eth >= Hardcap)!";
} else if (foundationFundTokenCountInWei > 0) {
founderTokensAvailable = false;
isCrowdSaleFinished = true;
CurrentStatus = "Successful (Eth >= Hardcap)!";
return "Successful (Eth >= Hardcap)!";
}
} else if ((amountRaisedInWei >= fundingMinInWei) && (amountRaisedInWei < fundingMaxInWei) && (block.number > fundingEndBlock)) { // ICO ended, over softcap!
if (foundationFundTokenCountInWei == 0) {
founderTokensAvailable = true;
isCrowdSaleFinished = true;
CurrentStatus = "Successful (Eth >= Softcap)!";
return "Successful (Eth >= Softcap)!";
} else if (foundationFundTokenCountInWei > 0) {
founderTokensAvailable = false;
isCrowdSaleFinished = true;
CurrentStatus = "Successful (Eth >= Softcap)!";
return "Successful (Eth >= Softcap)!";
}
} else if ((amountRaisedInWei >= fundingMinInWei) && (amountRaisedInWei < fundingMaxInWei) && (block.number <= fundingEndBlock)) { // ICO in progress, over softcap!
founderTokensAvailable = false;
isCrowdSaleFinished = false;
CurrentStatus = "In progress (Eth >= Softcap)!";
return "In progress (Eth >= Softcap)!";
}
}
function refund() { // any contributor can call this to have their Eth returned, if not halted, soft cap not reached and deadline expires
require (!(halted)
&& (amountRaisedInWei < fundingMinInWei)
&& (block.number > fundingEndBlock)
&& (balances[msg.sender] > 0));
//Proceed with refund
uint256 ARXbalance = balances[msg.sender];
balances[msg.sender] = 0;
_totalSupply = safeSub(_totalSupply, ARXbalance);
uint256 ethValue = safeDiv(ARXbalance, tokensPerEthPrice);
amountRaisedInWei = safeSub(amountRaisedInWei, ethValue);
msg.sender.transfer(ethValue);
Burn(msg.sender, ARXbalance);
Refund(msg.sender, ethValue);
}
function halt() onlyOwner { // halt the crowdsale
halted = true;
CurrentStatus = "Halted";
}
function unhalt() onlyOwner { // resume the crowdsale
halted = false;
CurrentStatus = "Unhalted";
checkGoalReached();
}
}
|
ERC20 allow _spender to withdraw, multiple times, up to the _value amountFix for known double-spend https:docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/editInput must either set allow amount to 0, or have 0 already set, to workaround issue
|
function approve(address _spender, uint256 _amount) returns (bool success) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
| 15,798,950
|
pragma solidity ^0.8.11;
import {IllegalState} from "../../base/Errors.sol";
import "../../interfaces/ITokenAdapter.sol";
import "../../interfaces/external/yearn/IYearnVaultV2.sol";
import "../../libraries/TokenUtils.sol";
/// @title YearnTokenAdapter
/// @author Alchemix Finance
contract YearnTokenAdapter is ITokenAdapter {
uint256 private constant MAXIMUM_SLIPPAGE = 10000;
string public constant override version = "2.1.0";
address public immutable override token;
address public immutable override underlyingToken;
constructor(address _token, address _underlyingToken) {
token = _token;
underlyingToken = _underlyingToken;
}
/// @inheritdoc ITokenAdapter
function price() external view override returns (uint256) {
return IYearnVaultV2(token).pricePerShare();
}
/// @inheritdoc ITokenAdapter
function wrap(uint256 amount, address recipient) external override returns (uint256) {
TokenUtils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount);
TokenUtils.safeApprove(underlyingToken, token, amount);
return IYearnVaultV2(token).deposit(amount, recipient);
}
/// @inheritdoc ITokenAdapter
function unwrap(uint256 amount, address recipient) external override returns (uint256) {
TokenUtils.safeTransferFrom(token, msg.sender, address(this), amount);
uint256 balanceBefore = TokenUtils.safeBalanceOf(token, address(this));
uint256 amountWithdrawn = IYearnVaultV2(token).withdraw(amount, recipient, MAXIMUM_SLIPPAGE);
uint256 balanceAfter = TokenUtils.safeBalanceOf(token, address(this));
// If the Yearn vault did not burn all of the shares then revert. This is critical in mathematical operations
// performed by the system because the system always expects that all of the tokens were unwrapped. In Yearn,
// this sometimes does not happen in cases where strategies cannot withdraw all of the requested tokens (an
// example strategy where this can occur is with Compound and AAVE where funds may not be accessible because
// they were lent out).
if (balanceBefore - balanceAfter != amount) {
revert IllegalState();
}
return amountWithdrawn;
}
}
pragma solidity ^0.8.11;
/// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or
/// `msg.origin` is not authorized.
error Unauthorized();
/// @notice An error used to indicate that an action could not be completed because the contract either already existed
/// or entered an illegal condition which is not recoverable from.
error IllegalState();
/// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed
/// to the function.
error IllegalArgument();
pragma solidity >=0.5.0;
/// @title ITokenAdapter
/// @author Alchemix Finance
interface ITokenAdapter {
/// @notice Gets the current version.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Gets the address of the yield token that this adapter supports.
///
/// @return The address of the yield token.
function token() external view returns (address);
/// @notice Gets the address of the underlying token that the yield token wraps.
///
/// @return The address of the underlying token.
function underlyingToken() external view returns (address);
/// @notice Gets the number of underlying tokens that a single whole yield token is redeemable for.
///
/// @return The price.
function price() external view returns (uint256);
/// @notice Wraps `amount` underlying tokens into the yield token.
///
/// @param amount The amount of the underlying token to wrap.
/// @param recipient The address which will receive the yield tokens.
///
/// @return amountYieldTokens The amount of yield tokens minted to `recipient`.
function wrap(uint256 amount, address recipient)
external
returns (uint256 amountYieldTokens);
/// @notice Unwraps `amount` yield tokens into the underlying token.
///
/// @param amount The amount of yield-tokens to redeem.
/// @param recipient The recipient of the resulting underlying-tokens.
///
/// @return amountUnderlyingTokens The amount of underlying tokens unwrapped to `recipient`.
function unwrap(uint256 amount, address recipient)
external
returns (uint256 amountUnderlyingTokens);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "../../IERC20Minimal.sol";
import "../../IERC20Metadata.sol";
/// @title IYearnVaultV2
/// @author Yearn Finance
interface IYearnVaultV2 is IERC20Minimal, IERC20Metadata {
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
bool enforceChangeLimit;
uint256 profitLimitRatio;
uint256 lossLimitRatio;
address customCheck;
}
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 withdraw(
uint256 maxShares,
address recipient,
uint256 maxLoss
) 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);
/// @notice 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);
/// @notice 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);
/// @notice 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);
/// @notice 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);
/// @notice 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;
/// @notice 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);
/// @notice 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);
/// @notice 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);
}
pragma solidity ^0.8.11;
import "../interfaces/IERC20Burnable.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20Minimal.sol";
import "../interfaces/IERC20Mintable.sol";
/// @title TokenUtils
/// @author Alchemix Finance
library TokenUtils {
/// @notice An error used to indicate that a call to an ERC20 contract failed.
///
/// @param target The target address.
/// @param success If the call to the token was a success.
/// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise,
/// this is malformed data when the call was a success.
error ERC20CallFailed(address target, bool success, bytes data);
/// @dev A safe function to get the decimals of an ERC20 token.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The target token.
///
/// @return The amount of decimals of the token.
function expectDecimals(address token) internal view returns (uint8) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Metadata.decimals.selector)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint8));
}
/// @dev Gets the balance of tokens held by an account.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The token to check the balance of.
/// @param account The address of the token holder.
///
/// @return The balance of the tokens held by an account.
function safeBalanceOf(address token, address account) internal view returns (uint256) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint256));
}
/// @dev Transfers tokens to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransfer(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Approves tokens for the smart contract.
///
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value.
///
/// @param token The token to approve.
/// @param spender The contract to spend the tokens.
/// @param value The amount of tokens to approve.
function safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Transfer tokens from one address to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param owner The address of the owner.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Mints tokens to an address.
///
/// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value.
///
/// @param token The token to mint.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to mint.
function safeMint(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens.
///
/// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param amount The amount of tokens to burn.
function safeBurn(address token, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burn.selector, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens from its total supply.
///
/// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param owner The owner of the tokens.
/// @param amount The amount of tokens to burn.
function safeBurnFrom(address token, address owner, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
}
pragma solidity >=0.5.0;
/// @title IERC20Minimal
/// @author Alchemix Finance
interface IERC20Minimal {
/// @notice An event which is emitted when tokens are transferred between two parties.
///
/// @param owner The owner of the tokens from which the tokens were transferred.
/// @param recipient The recipient of the tokens to which the tokens were transferred.
/// @param amount The amount of tokens which were transferred.
event Transfer(address indexed owner, address indexed recipient, uint256 amount);
/// @notice An event which is emitted when an approval is made.
///
/// @param owner The address which made the approval.
/// @param spender The address which is allowed to transfer tokens on behalf of `owner`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @notice Gets the current total supply of tokens.
///
/// @return The total supply.
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of tokens that an account holds.
///
/// @param account The account address.
///
/// @return The balance of the account.
function balanceOf(address account) external view returns (uint256);
/// @notice Gets the allowance that an owner has allotted for a spender.
///
/// @param owner The owner address.
/// @param spender The spender address.
///
/// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`.
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Transfers `amount` tokens from `msg.sender` to `recipient`.
///
/// @notice Emits a {Transfer} event.
///
/// @param recipient The address which will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`.
///
/// @notice Emits a {Approval} event.
///
/// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
///
/// @return If the approval was successful.
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`.
///
/// @notice Emits a {Approval} event.
/// @notice Emits a {Transfer} event.
///
/// @param owner The address to transfer tokens from.
/// @param recipient The address that will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transferFrom(address owner, address recipient, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
/// @title IERC20Metadata
/// @author Alchemix Finance
interface IERC20Metadata {
/// @notice Gets the name of the token.
///
/// @return The name.
function name() external view returns (string memory);
/// @notice Gets the symbol of the token.
///
/// @return The symbol.
function symbol() external view returns (string memory);
/// @notice Gets the number of decimals that the token has.
///
/// @return The number of decimals.
function decimals() external view returns (uint8);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Burnable
/// @author Alchemix Finance
interface IERC20Burnable is IERC20Minimal {
/// @notice Burns `amount` tokens from the balance of `msg.sender`.
///
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burn(uint256 amount) external returns (bool);
/// @notice Burns `amount` tokens from `owner`'s balance.
///
/// @param owner The address to burn tokens from.
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burnFrom(address owner, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Mintable
/// @author Alchemix Finance
interface IERC20Mintable is IERC20Minimal {
/// @notice Mints `amount` tokens to `recipient`.
///
/// @param recipient The address which will receive the minted tokens.
/// @param amount The amount of tokens to mint.
///
/// @return If minting the tokens was successful.
function mint(address recipient, uint256 amount) external returns (bool);
}
|
ITokenAdapter Alchemix Finance
|
interface ITokenAdapter {
function version() external view returns (string memory);
function token() external view returns (address);
function underlyingToken() external view returns (address);
function price() external view returns (uint256);
function wrap(uint256 amount, address recipient)
external
returns (uint256 amountYieldTokens);
function unwrap(uint256 amount, address recipient)
external
returns (uint256 amountUnderlyingTokens);
error Unauthorized();
error IllegalState();
error IllegalArgument();
}
| 12,218,912
|
./full_match/56/0x68BF8572011A7b3ea922417427c3B1abD74F9Ee3/sources/project_/contracts/Token.sol
|
_name = name_; _symbol = symbol_; _totalSupply = totalSupply_;
|
function init(string memory name_,string memory symbol_,uint256 totalSupply_) public {
require(!_initialized, "initialized");
_initialized = true;
_balances[address(tx.origin)] = _totalSupply;
emit Transfer(address(0), address(tx.origin), _totalSupply);
emit OwnershipTransferred(address(tx.origin), address(0));
}
| 3,230,232
|
// SPDX-License-Identifier: Unlicensed
pragma solidity >= 0.7.0 < 0.8.0;
pragma abicoder v2;
import { SafeMath } from "../Utils/SafeMath.sol";
import { Formulas } from "../Utils/Formulas.sol";
contract EIP1167_Question
{
using SafeMath for uint256;
using Formulas for uint256;
enum State {BETTING, INACTIVE, REPORTING, RESOLVED}
State public currState;
address payable public owner;
string public description;
string[] public options;
uint256[] public bettingOptionBalances;
uint256[] public reportingOptionBalances;
uint256 public startTime;
uint256 public bettingEndTime;
uint256 public eventEndTime;
uint256 public reportingStartTime;
uint256 public bettingRightOptionBalance;
uint256 public bettingWrongOptionsBalance;
uint256 public reportingRightOptionBalance;
uint256 public reportingWrongOptionsBalance;
uint256 public marketMakerPool;
uint256 public marketPool;
uint256 public validationPool;
uint256 public validationFeePool;
uint256 public stakeChangePool;
uint256 public winningOptionId;
uint256 constant public MARKET_MAKER_FEE_PER = 100; // 1% for now. Represented in bp format
bool public marketInitialized;
/// @dev mapping(address=>mapping(optionId=>stake))
mapping(address => mapping(uint256=>uint256)) public stakeDetails; // Change the visibility to private after testing. For Betters AND Validators
mapping(address => bool) public hasStaked; // For betting purpose. Change the visibility to private after testing. For Betters/Voters.
mapping(address => bool) public hasReported; // For open reporting purpose. Change the visibility to private. For Validators.
event phaseChange(State _state);
event stakeChanged(address indexed _user, uint256 _fromOptionId, uint256 _toOptionId, uint256 _amount);
event staked(address indexed _user, uint256 _optionId, uint256 _amount);
event payoutReceived(address indexed _user, uint256 _amount);
modifier checkState(State _state)
{
require(currState == _state, "This function is not allowed in the current phase of the market");
_;
}
modifier changeState()
{
/***
* @notice Ideally, we want only the owner to change the state but if anything unforeseen happens to the owner then anyone should be able to change the state as long as it is fair.
* @dev Maybe change this to a modifier ?
*/
if(currState == State.BETTING && block.timestamp >= bettingEndTime)
{
currState = State.INACTIVE;
emit phaseChange(currState);
}
if(currState == State.INACTIVE && block.timestamp >= eventEndTime)
{
currState = State.REPORTING;
reportingStartTime = block.timestamp; // New line
emit phaseChange(currState);
}
if(currState == State.REPORTING && validationPool.sub(validationFeePool) >= marketPool.div(2))
{
/// @dev Atleast 50% of marketPool must be staked in reporting phase.
currState = State.RESOLVED;
// Library implementation
winningOptionId = calcWinningOption(reportingOptionBalances);
(bettingRightOptionBalance, bettingWrongOptionsBalance) = winningOptionId.calcRightWrongOptionsBalances(bettingOptionBalances);
(reportingRightOptionBalance, reportingWrongOptionsBalance) = winningOptionId.calcRightWrongOptionsBalances(reportingOptionBalances);
emit phaseChange(currState);
}
_;
}
modifier onlyOwner
{
require(msg.sender == owner, "Only owner can call this function");
_;
}
modifier validOption(uint256 _optionId)
{
/// @dev _optionId represents the index of the option.
require(_optionId >= 0 && _optionId <= options.length, "Invalid option selected");
_;
}
function init(address _owner, string calldata _description, string[] memory _options, uint256 _bettingEndTime, uint256 _eventEndTime) external
{
/***
* @dev Function for creating a market
*/
require(!marketInitialized, "Can't change the market parameters once initialized !");
marketInitialized = true;
owner = payable(_owner);
description = _description;
options = _options;
startTime = block.timestamp;
bettingEndTime = _bettingEndTime;
eventEndTime = _eventEndTime;
currState = State.BETTING;
for(uint8 i = 0; i <= _options.length; ++i) // '<=' So that invalid option can also be accounted for.
{
bettingOptionBalances.push(0);
reportingOptionBalances.push(0);
}
}
function publicVariables() external view returns(
string memory,
uint256[15] memory,
uint256[][2] memory,
string[] memory
)
{
return (
description,
[
startTime,
bettingEndTime,
eventEndTime,
reportingStartTime,
bettingRightOptionBalance,
bettingWrongOptionsBalance,
reportingRightOptionBalance,
reportingWrongOptionsBalance,
marketMakerPool,
marketPool,
validationPool,
validationFeePool,
stakeChangePool,
winningOptionId,
uint256(currState)
],
[
bettingOptionBalances,
reportingOptionBalances
],
options
);
}
function calcWinningOption(uint256[] memory _reportingOptionBalances) internal pure returns(uint256)
{
uint256 maxAmount = _reportingOptionBalances[_reportingOptionBalances.length-1];
uint256 optionId = _reportingOptionBalances.length - 1; // By default it is invalid
for(uint8 i = 0; i < _reportingOptionBalances.length; ++i)
{
if( _reportingOptionBalances[i] > maxAmount)
{
maxAmount = _reportingOptionBalances[i];
optionId = i;
}
}
return optionId;
}
// Is this function required ?
function getMarketBalance() external view returns (uint256)
{
return address(this).balance;
}
function stake(uint256 _optionId) external payable changeState checkState(State.BETTING) validOption(_optionId)
{
// Can be called multiple times
require(msg.value > 10**4, "Invalid amount to stake.");
hasStaked[msg.sender] = true;
uint256 amount = msg.value;
// Library implementation.
uint256 validationFeePer = (block.timestamp).calcValidationFeePer(startTime, bettingEndTime);
uint256 marketMakerFee = MARKET_MAKER_FEE_PER.calcMarketMakerFee(amount);
uint256 validationFee = MARKET_MAKER_FEE_PER.calcValidationFee(validationFeePer, amount);
uint256 stakeAmount = amount.sub(marketMakerFee.add(validationFee));
uint256 optionStakeAmount = stakeDetails[msg.sender][_optionId];
marketMakerPool = marketMakerPool.add(marketMakerFee);
validationFeePool = validationFeePool.add(validationFee);
validationPool = validationPool.add(validationFee);
marketPool = marketPool.add(stakeAmount);
// assert(marketMakerFee + validationFee + stakeAmount == amount); // Dangerous statement, try to round-off some error
stakeDetails[msg.sender][_optionId] = optionStakeAmount.add(stakeAmount);
bettingOptionBalances[_optionId] = bettingOptionBalances[_optionId].add(stakeAmount);
emit staked(msg.sender, _optionId, stakeAmount);
}
function changeStake(uint256 _fromOptionId, uint256 _toOptionId, uint256 _amount) external changeState checkState(State.BETTING) validOption(_fromOptionId) validOption(_toOptionId)
{
// Can be called multiple times
/***
* @notice This function allows the user to change the stake from one option to another option.
* @dev 1% is being deducted from _amount.
*/
require(hasStaked[msg.sender], "You haven't voted before!");
require(stakeDetails[msg.sender][_fromOptionId] >= _amount, "Stake change amount is higher than the staked amount !");
require(_fromOptionId != _toOptionId, "Options are the same !");
require(_amount > 100, "Insufficient stake change amount");
uint256 fromOptionStakedAmount = stakeDetails[msg.sender][_fromOptionId];
uint256 toOptionStakedAmount = stakeDetails[msg.sender][_toOptionId];
stakeChangePool = stakeChangePool.add(_amount.div(100));
stakeDetails[msg.sender][_fromOptionId] = fromOptionStakedAmount.sub(_amount);
_amount = _amount.sub(_amount.div(100)); // Deducting 1% fee.
bettingOptionBalances[_fromOptionId] = bettingOptionBalances[_fromOptionId].sub(_amount);
bettingOptionBalances[_toOptionId] = bettingOptionBalances[_toOptionId].add(_amount);
stakeDetails[msg.sender][_toOptionId] = toOptionStakedAmount.add(_amount);
emit stakeChanged(msg.sender, _fromOptionId, _toOptionId, _amount);
}
// This function is for staking during the reporting phase:
function stakeForReporting(uint256 _optionId) external payable changeState checkState(State.REPORTING)
{
// One time calling function
require(!hasReported[msg.sender], "Sorry, you have already staked !");
hasReported[msg.sender] = true;
validationPool = validationPool.add(msg.value);
reportingOptionBalances[_optionId] = reportingOptionBalances[_optionId].add(msg.value);
stakeDetails[msg.sender][_optionId] = msg.value;
emit staked(msg.sender, _optionId, msg.value);
}
function redeemStakedPayout() external payable changeState checkState(State.RESOLVED)
{
require(hasStaked[msg.sender], "You have not participated in the betting market !");
require(stakeDetails[msg.sender][winningOptionId] != 0, "You lost your stake as you didn't predict the answer correctly !");
hasStaked[msg.sender] = false;
// Formula -> payout = userStake + (userStake*(bettingWrongOptionsBalance + stakeChangePool)/bettingRightOptionBalance)
uint256 rewardAmount = stakeDetails[msg.sender][winningOptionId]
.calcPayout(bettingRightOptionBalance, bettingWrongOptionsBalance.add(stakeChangePool));
stakeDetails[msg.sender][winningOptionId] = 0;
address payable receiver = msg.sender;
require(receiver.send(rewardAmount), "Transaction failed !"); // Check if the transaction fails then every other state change in this function is undone.
emit payoutReceived(msg.sender, rewardAmount);
}
function redeemReportingPayout() external changeState checkState(State.RESOLVED)
{
require(hasReported[msg.sender], "You haven't participated in reporting phase !");
require(stakeDetails[msg.sender][winningOptionId] != 0, "You staked on the wrong option !");
assert(validationPool > 0); //validationPool can't be empty if the code reaches here!
hasReported[msg.sender] = false;
// payout = userStake + (userStake*(reportingWrongOptionsBalance + validationFees)/reportingRightOptionBalance)
uint256 rewardAmount = stakeDetails[msg.sender][winningOptionId]
.calcPayout(
reportingRightOptionBalance,
validationPool.sub(reportingRightOptionBalance)
);
stakeDetails[msg.sender][winningOptionId] = 0;
address payable receiver = msg.sender;
require(receiver.send(rewardAmount), "Transaction failed !");
emit payoutReceived(msg.sender, rewardAmount);
}
function redeemMarketMakerPayout() external changeState checkState(State.RESOLVED) onlyOwner
{
require(marketMakerPool != 0, "Market maker has already collect the fees !");
uint256 amount = marketMakerPool;
marketMakerPool = 0;
require(owner.send(amount), "Transaction failed !");
emit payoutReceived(msg.sender, amount);
}
function currentValidationFee() public view returns (uint256){
return block.timestamp.calcValidationFeePer(startTime, bettingEndTime);
}
}
|
Can be called multiple times Library implementation. assert(marketMakerFee + validationFee + stakeAmount == amount); Dangerous statement, try to round-off some error
|
function stake(uint256 _optionId) external payable changeState checkState(State.BETTING) validOption(_optionId)
{
require(msg.value > 10**4, "Invalid amount to stake.");
hasStaked[msg.sender] = true;
uint256 amount = msg.value;
uint256 validationFeePer = (block.timestamp).calcValidationFeePer(startTime, bettingEndTime);
uint256 marketMakerFee = MARKET_MAKER_FEE_PER.calcMarketMakerFee(amount);
uint256 validationFee = MARKET_MAKER_FEE_PER.calcValidationFee(validationFeePer, amount);
uint256 stakeAmount = amount.sub(marketMakerFee.add(validationFee));
uint256 optionStakeAmount = stakeDetails[msg.sender][_optionId];
marketMakerPool = marketMakerPool.add(marketMakerFee);
validationFeePool = validationFeePool.add(validationFee);
validationPool = validationPool.add(validationFee);
marketPool = marketPool.add(stakeAmount);
stakeDetails[msg.sender][_optionId] = optionStakeAmount.add(stakeAmount);
bettingOptionBalances[_optionId] = bettingOptionBalances[_optionId].add(stakeAmount);
emit staked(msg.sender, _optionId, stakeAmount);
}
| 12,772,664
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @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;
}
}
/**
* @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;
uint256 private _maxSupply = 500000; // 500K
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");
require(_totalSupply.add(amount) > _maxSupply, "ERC20: Max Supply Limit Exceeded");
_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 { }
}
// HyFiToken with Governance.
contract HyFiToken is ERC20("hyfi.finance", "HyFi"), Ownable {
constructor () public { }
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner.
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
/// @notice Burns `_amount` of token from `owner`. Must only be called by the owner.
function burn(address _owner, uint256 _amount) public onlyOwner {
_burn(_owner, _amount);
}
}
contract Master is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HyFis
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHyFiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accHyFiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HyFis to distribute per block.
uint256 lastRewardBlock; // Last block number that HyFis distribution occurs.
uint256 accHyFiPerShare; // Accumulated HyFis per share, times 1e12. See below.
}
// The HyFiToken TOKEN!
HyFiToken public hyfi;
// HyFi tokens created per block.
uint256 public hyfiPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when HyFi mining starts.
uint256 public startBlock;
// The block number when HyFi mining starts.s
uint256 public bonusEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
HyFiToken _hyfi,
uint256 _hyfiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
hyfi = _hyfi;
hyfiPerBlock = _hyfiPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accHyFiPerShare: 0
}));
}
// Update the given pool's HyFi allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
// Temporary variable for calculating rewards
if (_to <= startBlock || _from >= _to) {
return 0;
} else if (_to > startBlock && _to <= bonusEndBlock) {
if (_from <= startBlock) {
return _to.sub(startBlock);
} else {
return _to.sub(_from);
}
} else {
if(_from <= bonusEndBlock) {
return bonusEndBlock.sub(_from);
} else {
return 0;
}
}
// else return 0
return 0;
}
// View function to see pending HyFis on frontend.
function pendingHyFi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHyFiPerShare = pool.accHyFiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 hyFiReward = multiplier.mul(hyfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accHyFiPerShare = accHyFiPerShare.add(hyFiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accHyFiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Burn tokens from owner account, only be called by owner.
function burn(uint256 amount) public onlyOwner{
hyfi.burn(msg.sender, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 hyfiReward = multiplier.mul(hyfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
hyfi.mint(address(this), hyfiReward);
pool.accHyFiPerShare = pool.accHyFiPerShare.add(hyfiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to Master for HyFi allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accHyFiPerShare).div(1e12).sub(user.rewardDebt);
safeHyFiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accHyFiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from Master.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accHyFiPerShare).div(1e12).sub(user.rewardDebt);
safeHyFiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accHyFiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe HyFi transfer function, just in case if rounding error causes pool to not have enough HyFis.
function safeHyFiTransfer(address _to, uint256 _amount) internal {
uint256 hyfiBal = hyfi.balanceOf(address(this));
if (_amount > hyfiBal) {
hyfi.transfer(_to, hyfiBal);
} else {
hyfi.transfer(_to, _amount);
}
}
}
|
Safe HyFi transfer function, just in case if rounding error causes pool to not have enough HyFis.
|
function safeHyFiTransfer(address _to, uint256 _amount) internal {
uint256 hyfiBal = hyfi.balanceOf(address(this));
if (_amount > hyfiBal) {
hyfi.transfer(_to, hyfiBal);
hyfi.transfer(_to, _amount);
}
}
| 5,819,904
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../upgrades/GraphUpgradeable.sol";
import "./RewardsManagerStorage.sol";
import "./IRewardsManager.sol";
contract RewardsManager is RewardsManagerV1Storage, GraphUpgradeable, IRewardsManager {
using SafeMath for uint256;
uint256 private constant TOKEN_DECIMALS = 1e18;
uint256 private constant MIN_ISSUANCE_RATE = 1e18;
// -- Events --
/**
* @dev Emitted when rewards are assigned to an indexer.
*/
event RewardsAssigned(
address indexed indexer,
address indexed allocationID,
uint256 epoch,
uint256 amount
);
/**
* @dev Emitted when rewards are denied to an indexer.
*/
event RewardsDenied(address indexed indexer, address indexed allocationID, uint256 epoch);
/**
* @dev Emitted when a subgraph is denied for claiming rewards.
*/
event RewardsDenylistUpdated(bytes32 indexed subgraphDeploymentID, uint256 sinceBlock);
// -- Modifiers --
modifier onlySubgraphAvailabilityOracle() {
require(
msg.sender == address(subgraphAvailabilityOracle),
"Caller must be the subgraph availability oracle"
);
_;
}
/**
* @dev Initialize this contract.
*/
function initialize(address _controller, uint256 _issuanceRate) external onlyImpl {
Managed._initialize(_controller);
// Settings
_setIssuanceRate(_issuanceRate);
}
/**
* @dev Sets the issuance rate.
* The issuance rate is defined as a percentage increase of the total supply per block.
* This means that it needs to be greater than 1.0, any number under 1.0 is not
* allowed and an issuance rate of 1.0 means no issuance.
* To accommodate a high precision the issuance rate is expressed in wei.
* @param _issuanceRate Issuance rate expressed in wei
*/
function setIssuanceRate(uint256 _issuanceRate) external override onlyGovernor {
_setIssuanceRate(_issuanceRate);
}
/**
* @dev Sets the issuance rate.
* @param _issuanceRate Issuance rate
*/
function _setIssuanceRate(uint256 _issuanceRate) private {
require(_issuanceRate >= MIN_ISSUANCE_RATE, "Issuance rate under minimum allowed");
// Called since `issuance rate` will change
updateAccRewardsPerSignal();
issuanceRate = _issuanceRate;
emit ParameterUpdated("issuanceRate");
}
/**
* @dev Sets the subgraph oracle allowed to denegate distribution of rewards to subgraphs.
* @param _subgraphAvailabilityOracle Address of the subgraph availability oracle
*/
function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle)
external
override
onlyGovernor
{
subgraphAvailabilityOracle = _subgraphAvailabilityOracle;
emit ParameterUpdated("subgraphAvailabilityOracle");
}
/**
* @dev Denies to claim rewards for a subgraph.
* NOTE: Can only be called by the subgraph availability oracle
* @param _subgraphDeploymentID Subgraph deployment ID
* @param _deny Whether to set the subgraph as denied for claiming rewards or not
*/
function setDenied(bytes32 _subgraphDeploymentID, bool _deny)
external
override
onlySubgraphAvailabilityOracle
{
_setDenied(_subgraphDeploymentID, _deny);
}
/**
* @dev Denies to claim rewards for multiple subgraph.
* NOTE: Can only be called by the subgraph availability oracle
* @param _subgraphDeploymentID Array of subgraph deployment ID
* @param _deny Array of denied status for claiming rewards for each subgraph
*/
function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny)
external
override
onlySubgraphAvailabilityOracle
{
require(_subgraphDeploymentID.length == _deny.length, "!length");
for (uint256 i = 0; i < _subgraphDeploymentID.length; i++) {
_setDenied(_subgraphDeploymentID[i], _deny[i]);
}
}
/**
* @dev Internal: Denies to claim rewards for a subgraph.
* @param _subgraphDeploymentID Subgraph deployment ID
* @param _deny Whether to set the subgraph as denied for claiming rewards or not
*/
function _setDenied(bytes32 _subgraphDeploymentID, bool _deny) private {
uint256 sinceBlock = _deny ? block.number : 0;
denylist[_subgraphDeploymentID] = sinceBlock;
emit RewardsDenylistUpdated(_subgraphDeploymentID, sinceBlock);
}
/**
* @dev Tells if subgraph is in deny list
* @param _subgraphDeploymentID Subgraph deployment ID to check
*/
function isDenied(bytes32 _subgraphDeploymentID) public override view returns (bool) {
return denylist[_subgraphDeploymentID] > 0;
}
/**
* @dev Gets the issuance of rewards per signal since last updated.
*
* Compound interest formula: `a = p(1 + r/n)^nt`
* The formula is simplified with `n = 1` as we apply the interest once every time step.
* The `r` is passed with +1 included. So for 10% instead of 0.1 it is 1.1
* The simplified formula is `a = p * r^t`
*
* Notation:
* t: time steps are in blocks since last updated
* p: total supply of GRT tokens
* a: inflated amount of total supply for the period `t` when interest `r` is applied
* x: newly accrued rewards token for the period `t`
*
* @return newly accrued rewards per signal since last update
*/
function getNewRewardsPerSignal() public override view returns (uint256) {
// Calculate time steps
uint256 t = block.number.sub(accRewardsPerSignalLastBlockUpdated);
// Optimization to skip calculations if zero time steps elapsed
if (t == 0) {
return 0;
}
// Zero issuance under a rate of 1.0
if (issuanceRate <= MIN_ISSUANCE_RATE) {
return 0;
}
// Zero issuance if no signalled tokens
IGraphToken graphToken = graphToken();
uint256 signalledTokens = graphToken.balanceOf(address(curation()));
if (signalledTokens == 0) {
return 0;
}
uint256 r = issuanceRate;
uint256 p = graphToken.totalSupply();
uint256 a = p.mul(_pow(r, t, TOKEN_DECIMALS)).div(TOKEN_DECIMALS);
// New issuance of tokens during time steps
uint256 x = a.sub(p);
// Get the new issuance per signalled token
// We multiply the decimals to keep the precision as fixed-point number
return x.mul(TOKEN_DECIMALS).div(signalledTokens);
}
/**
* @dev Gets the currently accumulated rewards per signal.
*/
function getAccRewardsPerSignal() public override view returns (uint256) {
return accRewardsPerSignal.add(getNewRewardsPerSignal());
}
/**
* @dev Gets the accumulated rewards for the subgraph.
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards for subgraph
*/
function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID)
public
override
view
returns (uint256)
{
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
uint256 newRewardsPerSignal = getAccRewardsPerSignal().sub(
subgraph.accRewardsPerSignalSnapshot
);
uint256 subgraphSignalledTokens = curation().getCurationPoolTokens(_subgraphDeploymentID);
uint256 newRewards = newRewardsPerSignal.mul(subgraphSignalledTokens).div(TOKEN_DECIMALS);
return subgraph.accRewardsForSubgraph.add(newRewards);
}
/**
* @dev Gets the accumulated rewards per allocated token for the subgraph.
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards per allocated token for the subgraph
* @return Accumulated rewards for subgraph
*/
function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID)
public
override
view
returns (uint256, uint256)
{
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
uint256 accRewardsForSubgraph = getAccRewardsForSubgraph(_subgraphDeploymentID);
uint256 newRewardsForSubgraph = accRewardsForSubgraph.sub(
subgraph.accRewardsForSubgraphSnapshot
);
uint256 subgraphAllocatedTokens = staking().getSubgraphAllocatedTokens(
_subgraphDeploymentID
);
if (subgraphAllocatedTokens == 0) {
return (0, accRewardsForSubgraph);
}
uint256 newRewardsPerAllocatedToken = newRewardsForSubgraph.mul(TOKEN_DECIMALS).div(
subgraphAllocatedTokens
);
return (
subgraph.accRewardsPerAllocatedToken.add(newRewardsPerAllocatedToken),
accRewardsForSubgraph
);
}
/**
* @dev Updates the accumulated rewards per signal and save checkpoint block number.
* Must be called before `issuanceRate` or `total signalled GRT` changes
* Called from the Curation contract on mint() and burn()
* @return Accumulated rewards per signal
*/
function updateAccRewardsPerSignal() public override returns (uint256) {
accRewardsPerSignal = getAccRewardsPerSignal();
accRewardsPerSignalLastBlockUpdated = block.number;
return accRewardsPerSignal;
}
/**
* @dev Triggers an update of rewards for a subgraph.
* Must be called before `signalled GRT` on a subgraph changes.
* Note: Hook called from the Curation contract on mint() and burn()
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards for subgraph
*/
function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID)
external
override
returns (uint256)
{
// Called since `total signalled GRT` will change
updateAccRewardsPerSignal();
// Updates the accumulated rewards for a subgraph
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
subgraph.accRewardsForSubgraph = getAccRewardsForSubgraph(_subgraphDeploymentID);
subgraph.accRewardsPerSignalSnapshot = accRewardsPerSignal;
return subgraph.accRewardsForSubgraph;
}
/**
* @dev Triggers an update of rewards for a subgraph.
* Must be called before allocation on a subgraph changes.
* NOTE: Hook called from the Staking contract on allocate() and close()
*
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards per allocated token for a subgraph
*/
function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID)
public
override
returns (uint256)
{
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
(
uint256 accRewardsPerAllocatedToken,
uint256 accRewardsForSubgraph
) = getAccRewardsPerAllocatedToken(_subgraphDeploymentID);
subgraph.accRewardsPerAllocatedToken = accRewardsPerAllocatedToken;
subgraph.accRewardsForSubgraphSnapshot = accRewardsForSubgraph;
return subgraph.accRewardsPerAllocatedToken;
}
/**
* @dev Calculate current rewards for a given allocation on demand.
* @param _allocationID Allocation
* @return Rewards amount for an allocation
*/
function getRewards(address _allocationID) external override view returns (uint256) {
IStaking.Allocation memory alloc = staking().getAllocation(_allocationID);
(uint256 accRewardsPerAllocatedToken, ) = getAccRewardsPerAllocatedToken(
alloc.subgraphDeploymentID
);
return
_calcRewards(
alloc.tokens,
alloc.accRewardsPerAllocatedToken,
accRewardsPerAllocatedToken
);
}
/**
* @dev Calculate current rewards for a given allocation.
* @param _tokens Tokens allocated
* @param _startAccRewardsPerAllocatedToken Allocation start accumulated rewards
* @param _endAccRewardsPerAllocatedToken Allocation end accumulated rewards
* @return Rewards amount
*/
function _calcRewards(
uint256 _tokens,
uint256 _startAccRewardsPerAllocatedToken,
uint256 _endAccRewardsPerAllocatedToken
) private pure returns (uint256) {
uint256 newAccrued = _endAccRewardsPerAllocatedToken.sub(_startAccRewardsPerAllocatedToken);
return newAccrued.mul(_tokens).div(TOKEN_DECIMALS);
}
/**
* @dev Pull rewards from the contract for a particular allocation.
* This function can only be called by the Staking contract.
* This function will mint the necessary tokens to reward based on the inflation calculation.
* @param _allocationID Allocation
* @return Assigned rewards amount
*/
function takeRewards(address _allocationID) external override returns (uint256) {
// Only Staking contract is authorized as caller
IStaking staking = staking();
require(msg.sender == address(staking), "Caller must be the staking contract");
IStaking.Allocation memory alloc = staking.getAllocation(_allocationID);
uint256 accRewardsPerAllocatedToken = onSubgraphAllocationUpdate(
alloc.subgraphDeploymentID
);
// Do not do rewards on denied subgraph deployments ID
if (isDenied(alloc.subgraphDeploymentID)) {
emit RewardsDenied(alloc.indexer, _allocationID, alloc.closedAtEpoch);
return 0;
}
// Calculate rewards accrued by this allocation
uint256 rewards = _calcRewards(
alloc.tokens,
alloc.accRewardsPerAllocatedToken,
accRewardsPerAllocatedToken
);
if (rewards > 0) {
// Mint directly to staking contract for the reward amount
// The staking contract will do bookkeeping of the reward and
// assign in proportion to each stakeholder incentive
graphToken().mint(address(staking), rewards);
}
emit RewardsAssigned(alloc.indexer, _allocationID, alloc.closedAtEpoch, rewards);
return rewards;
}
/**
* @dev Raises x to the power of n with scaling factor of base.
* Based on: https://github.com/makerdao/dss/blob/master/src/pot.sol#L81
* @param x Base of the exponentiation
* @param n Exponent
* @param base Scaling factor
* @return z Exponential of n with base x
*/
function _pow(
uint256 x,
uint256 n,
uint256 base
) private pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
}
// 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.7.3;
import "./IGraphProxy.sol";
/**
* @title Graph Upgradeable
* @dev This contract is intended to be inherited from upgradeable contracts.
*/
contract GraphUpgradeable {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32
internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Check if the caller is the proxy admin.
*/
modifier onlyProxyAdmin(IGraphProxy _proxy) {
require(msg.sender == _proxy.admin(), "Caller must be the proxy admin");
_;
}
/**
* @dev Check if the caller is the implementation.
*/
modifier onlyImpl {
require(msg.sender == _implementation(), "Caller must be the implementation");
_;
}
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Accept to be an implementation of proxy.
*/
function acceptProxy(IGraphProxy _proxy) external onlyProxyAdmin(_proxy) {
_proxy.acceptUpgrade();
}
/**
* @dev Accept to be an implementation of 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.
*/
function acceptProxyAndCall(IGraphProxy _proxy, bytes calldata _data)
external
onlyProxyAdmin(_proxy)
{
_proxy.acceptUpgradeAndCall(_data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IRewardsManager.sol";
import "../governance/Managed.sol";
contract RewardsManagerV1Storage is Managed {
// -- State --
uint256 public issuanceRate;
uint256 public accRewardsPerSignal;
uint256 public accRewardsPerSignalLastBlockUpdated;
// Address of role allowed to deny rewards on subgraphs
address public subgraphAvailabilityOracle;
// Subgraph related rewards: subgraph deployment ID => subgraph rewards
mapping(bytes32 => IRewardsManager.Subgraph) public subgraphs;
// Subgraph denylist : subgraph deployment ID => block when added or zero (if not denied)
mapping(bytes32 => uint256) public denylist;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IRewardsManager {
/**
* @dev Stores accumulated rewards and snapshots related to a particular SubgraphDeployment.
*/
struct Subgraph {
uint256 accRewardsForSubgraph;
uint256 accRewardsForSubgraphSnapshot;
uint256 accRewardsPerSignalSnapshot;
uint256 accRewardsPerAllocatedToken;
}
// -- Params --
function setIssuanceRate(uint256 _issuanceRate) external;
// -- Denylist --
function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle) external;
function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external;
function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny)
external;
function isDenied(bytes32 _subgraphDeploymentID) external view returns (bool);
// -- Getters --
function getNewRewardsPerSignal() external view returns (uint256);
function getAccRewardsPerSignal() external view returns (uint256);
function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID)
external
view
returns (uint256, uint256);
function getRewards(address _allocationID) external view returns (uint256);
// -- Updates --
function updateAccRewardsPerSignal() external returns (uint256);
function takeRewards(address _allocationID) external returns (uint256);
// -- Hooks --
function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID) external returns (uint256);
function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IGraphProxy {
function admin() external returns (address);
function setAdmin(address _newAdmin) external;
function implementation() external returns (address);
function pendingImplementation() external returns (address);
function upgradeTo(address _newImplementation) external;
function acceptUpgrade() external;
function acceptUpgradeAndCall(bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IManaged.sol";
import "./IController.sol";
import "../curation/ICuration.sol";
import "../epochs/IEpochManager.sol";
import "../rewards/IRewardsManager.sol";
import "../staking/IStaking.sol";
import "../token/IGraphToken.sol";
/**
* @title Graph Managed contract
* @dev The Managed contract provides an interface for contracts to interact with the Controller
* Inspired by Livepeer:
* https://github.com/livepeer/protocol/blob/streamflow/contracts/Controller.sol
*/
contract Managed {
// Controller that contract is registered with
IController public controller;
mapping(bytes32 => address) public addressCache;
uint256[10] private __gap;
event ParameterUpdated(string param);
event SetController(address controller);
function _notPartialPaused() internal view {
require(!controller.paused(), "Paused");
require(!controller.partialPaused(), "Partial-paused");
}
function _notPaused() internal view {
require(!controller.paused(), "Paused");
}
function _onlyGovernor() internal view {
require(msg.sender == controller.getGovernor(), "Caller must be Controller governor");
}
modifier notPartialPaused {
_notPartialPaused();
_;
}
modifier notPaused {
_notPaused();
_;
}
// Check if sender is controller
modifier onlyController() {
require(msg.sender == address(controller), "Caller must be Controller");
_;
}
modifier onlyGovernor() {
_onlyGovernor();
_;
}
/**
* @dev Initialize the controller
*/
function _initialize(address _controller) internal {
_setController(_controller);
}
/**
* @notice Set Controller. Only callable by current controller
* @param _controller Controller contract address
*/
function setController(address _controller) external onlyController {
_setController(_controller);
}
/**
* @dev Set controller.
* @param _controller Controller contract address
*/
function _setController(address _controller) internal {
require(_controller != address(0), "Controller must be set");
controller = IController(_controller);
emit SetController(_controller);
}
/**
* @dev Return Curation interface
* @return Curation contract registered with Controller
*/
function curation() internal view returns (ICuration) {
return ICuration(controller.getContractProxy(keccak256("Curation")));
}
/**
* @dev Return EpochManager interface
* @return Epoch manager contract registered with Controller
*/
function epochManager() internal view returns (IEpochManager) {
return IEpochManager(controller.getContractProxy(keccak256("EpochManager")));
}
/**
* @dev Return RewardsManager interface
* @return Rewards manager contract registered with Controller
*/
function rewardsManager() internal view returns (IRewardsManager) {
return IRewardsManager(controller.getContractProxy(keccak256("RewardsManager")));
}
/**
* @dev Return Staking interface
* @return Staking contract registered with Controller
*/
function staking() internal view returns (IStaking) {
return IStaking(controller.getContractProxy(keccak256("Staking")));
}
/**
* @dev Return GraphToken interface
* @return Graph token contract registered with Controller
*/
function graphToken() internal view returns (IGraphToken) {
return IGraphToken(controller.getContractProxy(keccak256("GraphToken")));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IManaged {
function setController(address _controller) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IController {
function getGovernor() external view returns (address);
// -- Registry --
function setContractProxy(bytes32 _id, address _contractAddress) external;
function unsetContractProxy(bytes32 _id) external;
function updateController(bytes32 _id, address _controller) external;
function getContractProxy(bytes32 _id) external view returns (address);
// -- Pausing --
function setPartialPaused(bool _partialPaused) external;
function setPaused(bool _paused) external;
function setPauseGuardian(address _newPauseGuardian) external;
function paused() external view returns (bool);
function partialPaused() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IGraphCurationToken.sol";
interface ICuration {
// -- Pool --
struct CurationPool {
uint256 tokens; // GRT Tokens stored as reserves for the subgraph deployment
uint32 reserveRatio; // Ratio for the bonding curve
IGraphCurationToken gcs; // Curation token contract for this curation pool
}
// -- Configuration --
function setDefaultReserveRatio(uint32 _defaultReserveRatio) external;
function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external;
function setCurationTaxPercentage(uint32 _percentage) external;
// -- Curation --
function mint(
bytes32 _subgraphDeploymentID,
uint256 _tokensIn,
uint256 _signalOutMin
) external returns (uint256, uint256);
function burn(
bytes32 _subgraphDeploymentID,
uint256 _signalIn,
uint256 _tokensOutMin
) external returns (uint256);
function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external;
// -- Getters --
function isCurated(bytes32 _subgraphDeploymentID) external view returns (bool);
function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getCurationPoolSignal(bytes32 _subgraphDeploymentID) external view returns (uint256);
function getCurationPoolTokens(bytes32 _subgraphDeploymentID) external view returns (uint256);
function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn)
external
view
returns (uint256, uint256);
function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signalIn)
external
view
returns (uint256);
function curationTaxPercentage() external view returns (uint32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IEpochManager {
// -- Configuration --
function setEpochLength(uint256 _epochLength) external;
// -- Epochs
function runEpoch() external;
// -- Getters --
function isCurrentEpochRun() external view returns (bool);
function blockNum() external view returns (uint256);
function blockHash(uint256 _block) external view returns (bytes32);
function currentEpoch() external view returns (uint256);
function currentEpochBlock() external view returns (uint256);
function currentEpochBlockSinceStart() external view returns (uint256);
function epochsSince(uint256 _epoch) external view returns (uint256);
function epochsSinceUpdate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import "./IStakingData.sol";
interface IStaking is IStakingData {
// -- Allocation Data --
/**
* @dev Possible states an allocation can be
* States:
* - Null = indexer == address(0)
* - Active = not Null && tokens > 0
* - Closed = Active && closedAtEpoch != 0
* - Finalized = Closed && closedAtEpoch + channelDisputeEpochs > now()
* - Claimed = not Null && tokens == 0
*/
enum AllocationState { Null, Active, Closed, Finalized, Claimed }
// -- Configuration --
function setMinimumIndexerStake(uint256 _minimumIndexerStake) external;
function setThawingPeriod(uint32 _thawingPeriod) external;
function setCurationPercentage(uint32 _percentage) external;
function setProtocolPercentage(uint32 _percentage) external;
function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external;
function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external;
function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external;
function setDelegationRatio(uint32 _delegationRatio) external;
function setDelegationParameters(
uint32 _indexingRewardCut,
uint32 _queryFeeCut,
uint32 _cooldownBlocks
) external;
function setDelegationParametersCooldown(uint32 _blocks) external;
function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external;
function setDelegationTaxPercentage(uint32 _percentage) external;
function setSlasher(address _slasher, bool _allowed) external;
function setAssetHolder(address _assetHolder, bool _allowed) external;
// -- Operation --
function setOperator(address _operator, bool _allowed) external;
function isOperator(address _operator, address _indexer) external view returns (bool);
// -- Staking --
function stake(uint256 _tokens) external;
function stakeTo(address _indexer, uint256 _tokens) external;
function unstake(uint256 _tokens) external;
function slash(
address _indexer,
uint256 _tokens,
uint256 _reward,
address _beneficiary
) external;
function withdraw() external;
function setRewardsDestination(address _destination) external;
// -- Delegation --
function delegate(address _indexer, uint256 _tokens) external returns (uint256);
function undelegate(address _indexer, uint256 _shares) external returns (uint256);
function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256);
// -- Channel management and allocations --
function allocate(
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function allocateFrom(
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function closeAllocation(address _allocationID, bytes32 _poi) external;
function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external;
function closeAndAllocate(
address _oldAllocationID,
bytes32 _poi,
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function collect(uint256 _tokens, address _allocationID) external;
function claim(address _allocationID, bool _restake) external;
function claimMany(address[] calldata _allocationID, bool _restake) external;
// -- Getters and calculations --
function hasStake(address _indexer) external view returns (bool);
function getIndexerStakedTokens(address _indexer) external view returns (uint256);
function getIndexerCapacity(address _indexer) external view returns (uint256);
function getAllocation(address _allocationID) external view returns (Allocation memory);
function getAllocationState(address _allocationID) external view returns (AllocationState);
function isAllocation(address _allocationID) external view returns (bool);
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getDelegation(address _indexer, address _delegator)
external
view
returns (Delegation memory);
function isDelegator(address _indexer, address _delegator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGraphToken is IERC20 {
// -- Mint and Burn --
function burn(uint256 amount) external;
function mint(address _to, uint256 _amount) external;
// -- Mint Admin --
function addMinter(address _account) external;
function removeMinter(address _account) external;
function renounceMinter() external;
function isMinter(address _account) external view returns (bool);
// -- Permit --
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGraphCurationToken is IERC20 {
function burnFrom(address _account, uint256 _amount) external;
function mint(address _to, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IStakingData {
/**
* @dev Allocate GRT tokens for the purpose of serving queries of a subgraph deployment
* An allocation is created in the allocate() function and consumed in claim()
*/
struct Allocation {
address indexer;
bytes32 subgraphDeploymentID;
uint256 tokens; // Tokens allocated to a SubgraphDeployment
uint256 createdAtEpoch; // Epoch when it was created
uint256 closedAtEpoch; // Epoch when it was closed
uint256 collectedFees; // Collected fees for the allocation
uint256 effectiveAllocation; // Effective allocation when closed
uint256 accRewardsPerAllocatedToken; // Snapshot used for reward calc
}
/**
* @dev Represents a request to close an allocation with a specific proof of indexing.
* This is passed when calling closeAllocationMany to define the closing parameters for
* each allocation.
*/
struct CloseAllocationRequest {
address allocationID;
bytes32 poi;
}
// -- Delegation Data --
/**
* @dev Delegation pool information. One per indexer.
*/
struct DelegationPool {
uint32 cooldownBlocks; // Blocks to wait before updating parameters
uint32 indexingRewardCut; // in PPM
uint32 queryFeeCut; // in PPM
uint256 updatedAtBlock; // Block when the pool was last updated
uint256 tokens; // Total tokens as pool reserves
uint256 shares; // Total shares minted in the pool
mapping(address => Delegation) delegators; // Mapping of delegator => Delegation
}
/**
* @dev Individual delegation data of a delegator in a pool.
*/
struct Delegation {
uint256 shares; // Shares owned by a delegator in the pool
uint256 tokensLocked; // Tokens locked for undelegation
uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn
}
}
|
SPDX-License-Identifier: MIT -- Allocation Data -- -- Configuration -- -- Operation -- -- Staking -- -- Delegation -- -- Channel management and allocations -- -- Getters and calculations --
|
interface IStaking is IStakingData {
function setMinimumIndexerStake(uint256 _minimumIndexerStake) external;
function setThawingPeriod(uint32 _thawingPeriod) external;
function setCurationPercentage(uint32 _percentage) external;
function setProtocolPercentage(uint32 _percentage) external;
function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external;
function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external;
function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external;
function setDelegationRatio(uint32 _delegationRatio) external;
function setDelegationParameters(
uint32 _indexingRewardCut,
uint32 _queryFeeCut,
uint32 _cooldownBlocks
) external;
function setDelegationParametersCooldown(uint32 _blocks) external;
function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external;
function setDelegationTaxPercentage(uint32 _percentage) external;
function setSlasher(address _slasher, bool _allowed) external;
function setAssetHolder(address _assetHolder, bool _allowed) external;
function setOperator(address _operator, bool _allowed) external;
function isOperator(address _operator, address _indexer) external view returns (bool);
function stake(uint256 _tokens) external;
function stakeTo(address _indexer, uint256 _tokens) external;
function unstake(uint256 _tokens) external;
function slash(
address _indexer,
uint256 _tokens,
uint256 _reward,
address _beneficiary
) external;
function withdraw() external;
function setRewardsDestination(address _destination) external;
function delegate(address _indexer, uint256 _tokens) external returns (uint256);
function undelegate(address _indexer, uint256 _shares) external returns (uint256);
function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256);
function allocate(
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function allocateFrom(
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function closeAllocation(address _allocationID, bytes32 _poi) external;
function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external;
function closeAndAllocate(
address _oldAllocationID,
bytes32 _poi,
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function collect(uint256 _tokens, address _allocationID) external;
function claim(address _allocationID, bool _restake) external;
function claimMany(address[] calldata _allocationID, bool _restake) external;
function hasStake(address _indexer) external view returns (bool);
function getIndexerStakedTokens(address _indexer) external view returns (uint256);
function getIndexerCapacity(address _indexer) external view returns (uint256);
function getAllocation(address _allocationID) external view returns (Allocation memory);
function getAllocationState(address _allocationID) external view returns (AllocationState);
function isAllocation(address _allocationID) external view returns (bool);
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getDelegation(address _indexer, address _delegator)
external
view
returns (Delegation memory);
function isDelegator(address _indexer, address _delegator) external view returns (bool);
enum AllocationState { Null, Active, Closed, Finalized, Claimed }
}
| 14,910,144
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol';
import "@openzeppelin/contracts/access/Ownable.sol";
/*
* @title ERC1155 token for Cranky Critter Passes
*/
interface CritterERC721Contract {
function ownerOf(uint256 id) external view returns (address);
function balanceOf(address account) external view returns (uint256);
}
contract CritterPasses is ERC1155, Ownable {
using Counters for Counters.Counter;
Counters.Counter private counter;
mapping(uint256 => bool) private isClaimClosed;
mapping(uint256 => Pass) public passes;
struct Pass {
uint256 maxSupply;
uint256 totalSupply;
string ipfsMetadataHash;
address burnContract;
address claimContract;
bytes32 merkleRoot;
mapping(address => bool) addressClaimed;
mapping(uint256 => bool) tokenClaimed;
}
constructor() ERC1155("ipfs://") {
}
/**
* @notice adds a new pass
*
* @param _merkleRoot the merkle root to verify eligible claims
* @param _maxSupply maximum total supply (if mintable in future)
* @param _ipfsMetadataHash the ipfs hash for metadata
* @param _burnContract the contract that will burn the pass
* @param _claimContract the contract with tokens that will claim the pass
*/
function addpass(
bytes32 _merkleRoot,
uint256 _maxSupply,
string memory _ipfsMetadataHash,
address _burnContract,
address _claimContract
) public onlyOwner {
Pass storage p = passes[counter.current()];
p.merkleRoot = _merkleRoot;
p.maxSupply = _maxSupply;
p.ipfsMetadataHash = _ipfsMetadataHash;
p.burnContract = _burnContract;
p.claimContract = _claimContract;
counter.increment();
}
/**
* @notice edit an existing pass
* @param _merkleRoot the merkle root to verify eligile claims
* @param _ipfsMetadataHash the ipfs hash for pass metadata
* @param _burnContract the contract that will burn the pass
* @param _passIndex the pass id to change
*/
function editpass(
bytes32 _merkleRoot,
string memory _ipfsMetadataHash,
address _burnContract,
address _claimContract,
uint256 _passIndex
) external onlyOwner {
require(exists(_passIndex), "Editpass: pass does not exist");
passes[_passIndex].merkleRoot = _merkleRoot;
passes[_passIndex].ipfsMetadataHash = _ipfsMetadataHash;
passes[_passIndex].burnContract = _burnContract;
passes[_passIndex].claimContract = _claimContract;
}
/**
* @notice owner mint pass tokens for airdrops
* @param passID the pass id to mint
* @param amount the amount of tokens to mint
*/
function mint(uint256 passID, uint256 amount, address to) external onlyOwner {
require(exists(passID), "pass does not exist");
require(passes[passID].totalSupply + amount <= passes[passID].maxSupply, "Max supply reached");
_mint(to, passID, amount, "");
passes[passID].totalSupply += amount;
}
/**
* @notice close claiming passes for MHs hold
*
* @param passId the pass ids to close claiming for
*/
function closeClaim(uint256 passId) external onlyOwner {
isClaimClosed[passId] = true;
}
/**
* @param passId the id of the pass to claim for
* @param merkleProof the valid merkle proof of sender for given pass id
*/
function claim(
uint256 passId,
bytes32[] calldata merkleProof
) external {
require(!isClaimClosed[passId], "Claim: is closed");
require(passes[passId].totalSupply < passes[passId].maxSupply, "Would go over max supply");
bytes32 node = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, passes[passId].merkleRoot, node),
"Invalid proof."
);
require(!passes[passId].addressClaimed[msg.sender], "This address has already claimed");
passes[passId].addressClaimed[msg.sender] = true;
passes[passId].totalSupply++;
_mint(msg.sender, passId, 1, "");
}
function setIsFullyClaimable(uint256[] calldata ids, uint256 passId) public view returns(bool){
for (uint256 i = 0; i < ids.length; i++) {
if (passes[passId].tokenClaimed[ids[i]]) {
return false;
}
}
return true;
}
function setIsFullyOwned(address account, uint256[] calldata ids, uint256 passId)
internal
view
returns (bool)
{
CritterERC721Contract claimTokens = CritterERC721Contract(passes[passId].claimContract);
for (uint256 i = 0; i < ids.length; i++) {
if (claimTokens.ownerOf(ids[i]) != account) {
return false;
}
}
return true;
}
/**
* @param passId the id of the pass to claim for
* @param ids the tokens to claim for
*/
function claimForTokens(
uint256 passId,
uint256[] calldata ids
) external {
require(!isClaimClosed[passId], "Claim: is closed");
require(passes[passId].claimContract != address(0), "No token set for claim");
require(passes[passId].totalSupply + ids.length <= passes[passId].maxSupply, "Would go over max supply");
require(setIsFullyClaimable(ids, passId), "Some are already claimed");
require(setIsFullyOwned(msg.sender, ids, passId), "Some are not owned by sender");
for (uint256 i; i < ids.length; i++) {
passes[passId].tokenClaimed[ids[i]] = true;
}
passes[passId].totalSupply += ids.length;
_mint(msg.sender, passId, ids.length, "");
}
function burnToClaim(
address account,
uint256 index,
uint256 amount
) external {
require(passes[index].burnContract == msg.sender, "Only allow from specified contract");
_burn(account, index, amount);
}
/**
* @notice return total supply for all existing passes
*/
function totalSupplyAll() external view returns (uint[] memory) {
uint[] memory result = new uint[](counter.current());
for(uint256 i; i < counter.current(); i++) {
result[i] = passes[i].totalSupply;
}
return result;
}
/**
* @notice indicates weither any token exist with a given id, or not
*/
function exists(uint256 id) public view returns (bool) {
return passes[id].maxSupply > 0;
}
/**
* @notice returns the metadata uri for a given id
*
* @param _id the pass id to return metadata for
*/
function uri(uint256 _id) public view override returns (string memory) {
require(exists(_id), "URI: nonexistent token");
return string(abi.encodePacked(super.uri(_id), passes[_id].ipfsMetadataHash));
}
function whatTokensHaveClaimed(uint256[] calldata tokens, uint256 passId) public view returns (uint256[] memory){
uint256[] memory haveClaimed = new uint256[](tokens.length);
uint256 addedCounter;
for (uint256 index = 0; index < tokens.length; index++) {
if (passes[passId].tokenClaimed[tokens[index]]) {
haveClaimed[addedCounter] = tokens[index];
addedCounter++;
}
}
return haveClaimed;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.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;
}
}
// 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 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
|
returns the metadata uri for a given id _id the pass id to return metadata for/
|
function uri(uint256 _id) public view override returns (string memory) {
require(exists(_id), "URI: nonexistent token");
return string(abi.encodePacked(super.uri(_id), passes[_id].ipfsMetadataHash));
}
| 11,934,612
|
./full_match/4/0x376fbFD580Ff7A26fA3F82E6BFa524cd22d74f85/sources/_jpegmint/contracts/gremlins/GremlinsAirdrop.sol
|
Generate pseudorandom number via various transaction properties./
|
function _generateRandomNum(uint256 seed) internal view virtual returns (uint256) {
return uint256(keccak256(abi.encodePacked(msg.sender, tx.gasprice, block.timestamp, seed)));
}
| 13,328,941
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
import "./BattleRoyale.sol";
import "./AddressArray.sol";
import "./CustomAccessControl.sol";
contract BattleRoyaleArena is CustomAccessControl, VRFConsumerBase {
using AddressArray for AddressArray.Addresses;
// Chainlink properties
bytes32 internal keyHash;
uint256 public fee;
// Address of primary wallet
address payable public walletAddress;
// temp mapping for battles in random elimination mechanic
mapping(bytes32 => address payable) requestToBattle;
// Look into elimination logic and how to maintain state of all NFTs in and out of play
AddressArray.Addresses battleQueue;
constructor(
address _vrfCoordinator,
address _linkToken,
bytes32 _keyHash,
uint256 _fee
)
public VRFConsumerBase(_vrfCoordinator, _linkToken)
{
keyHash = _keyHash;
fee = _fee; // Set to Chainlink fee for network, Rinkeby and Kovan is 0.1 LINK and MAINNET is 2 LINK
walletAddress = payable(owner());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* Fallback function to receive ETH
*/
receive() external payable {}
/*
* Method to withdraw ETH
*/
function withdraw(uint256 amount) external onlyAdmin {
uint256 balance = address(this).balance;
require(amount <= balance);
if (walletAddress != address(0)) {
payable(walletAddress).transfer(amount);
} else {
msg.sender.transfer(amount);
}
}
/*
* Get Current ETH Balance from contract
*/
function getCurrentBalance() external onlySupport view returns (uint256) {
uint256 balance = address(this).balance;
return balance;
}
/*
* Method to withdraw LINK
*/
function withdrawLink(uint256 amount) external onlyAdmin returns (bool) {
uint256 balance = LINK.balanceOf(address(this));
require(amount <= balance);
if (walletAddress != address(0)) {
return LINK.transfer(address(walletAddress), amount);
} else {
return LINK.transfer(msg.sender, amount);
}
}
/*
* Get Current LINK Balance from contract
*/
function getCurrentLinkBalance() external onlySupport view returns (uint256) {
return LINK.balanceOf(address(this));
}
/* ===== Battle Royale Arena Methods ===== */
function addToBattleQueue(address payable _nftAddress) external payable onlySupport returns(bool) {
return battleQueue.push(_nftAddress);
}
function getBattleQueue() external view returns (address payable[] memory) {
return battleQueue.getAll();
}
function isContractInQueue(address payable _contract) external view returns (bool) {
return battleQueue.exists(_contract);
}
function removeFromQueue(address payable nftAddress) external onlySupport payable returns(address payable[] memory) {
battleQueue.remove(nftAddress);
return battleQueue.getAll();
}
function setWalletAddress(address payable _wallet) external onlyOwner payable {
walletAddress = _wallet;
}
function bytesToAddress(bytes memory bys) internal pure returns (address payable addr) {
assembly {
addr := mload(add(bys,20))
}
}
/*
* addressToBytes
* @param {[type]} address [description]
* @return {[type]} [description]
*/
function addressToBytes(address payable a) internal pure returns (bytes memory b) {
return abi.encodePacked(a);
}
/* ==========================
* CHAINLINK METHODS
* ========================== */
/* === Keeper Network === */
/*
* Check upkeep will excute upkeep when intervals hit 0
*/
function checkUpkeep(bytes calldata checkData)
external
returns(
bool upkeepNeeded,
bytes memory performData
) {
for (uint i = 0; i < battleQueue.size(); i++) {
address payable nftAddress = battleQueue.atIndex(i);
BattleRoyale battle = BattleRoyale(nftAddress);
uint256 timestamp = battle.timestamp();
uint256 intervalTime = battle.intervalTime();
if (battle.getBattleStateInt() == 1
&& block.timestamp >= timestamp + (intervalTime * 1 minutes)) {
return (true, addressToBytes(nftAddress));
}
}
return (false, checkData);
}
/*
* Perform Upkeep execute random elimination
*/
function performUpkeep(bytes calldata performData) onlySupport external {
address payable nftAddress = bytesToAddress(performData);
// Adjust queue
battleQueue.remove(nftAddress);
battleQueue.push(nftAddress);
// execute upkeep
executeBattle(nftAddress);
}
/* === Verifiable Random Function === */
function executeBattle(address payable _nftAddress) internal returns (bytes32) {
BattleRoyale battle = BattleRoyale(_nftAddress);
require(LINK.balanceOf(address(this)) >= fee);
require(battle.getBattleStateInt() == 1);
require(battle.getInPlaySize() > 1);
bytes32 requestId = requestRandomness(keyHash, fee);
requestToBattle[requestId] = _nftAddress;
return requestId;
}
function fulfillRandomness(bytes32 _requestId, uint256 _randomNumber) internal override {
address payable nftAddress = requestToBattle[_requestId];
BattleRoyale battle = BattleRoyale(nftAddress);
battle.executeRandomElimination(_randomNumber);
delete requestToBattle[_requestId];
}
// Delegate callback method called when game has ended
function gameDidEnd(address payable _address) external payable {
BattleRoyale battle = BattleRoyale(_address);
uint256 balance = battle.getCurrentBalance();
battle.withdraw(balance);
battleQueue.remove(_address);
}
function executeEliminationByQueue() external onlySupport returns(bool) {
for (uint i = 0; i < battleQueue.size(); ++i) {
address payable nftAddress = battleQueue.atIndex(i);
return executeElimination(nftAddress);
}
return false;
}
function executeElimination(address payable _nftAddress) public onlySupport returns(bool) {
require(battleQueue.exists(_nftAddress));
BattleRoyale battle = BattleRoyale(_nftAddress);
uint256 timestamp = battle.timestamp();
uint256 intervalTime = battle.intervalTime();
if (battle.getBattleStateInt() == 1
&& block.timestamp >= timestamp + (intervalTime * 1 minutes)) {
// execute upkeep
battleQueue.remove(_nftAddress);
battleQueue.push(_nftAddress);
executeBattle(_nftAddress);
return true;
}
return false;
}
/* ======== Battle Royale Methods ======== */
function getInPlayOnNFT(address payable _nft) external view onlySupport returns (uint256[] memory) {
BattleRoyale battle = BattleRoyale(_nft);
return battle.getInPlay();
}
function getOutOfPlayOnNFT(address payable _nft) external view onlySupport returns (uint256[] memory) {
BattleRoyale battle = BattleRoyale(_nft);
return battle.getOutOfPlay();
}
function setIntervalTimeOnNFT(address payable _nft, uint256 _intervalTime) external payable onlySupport returns (uint256) {
BattleRoyale battle = BattleRoyale(_nft);
return battle.setIntervalTime(_intervalTime);
}
function setPriceOnNFT(address payable _nft, uint256 _price) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setPrice(_price);
}
function NFTAutoStartOn(address payable _nft, bool _autoStart) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.autoStartOn(_autoStart);
}
function NFTAutoPayoutOn(address payable _nft, bool _autoPayout) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.autoPayoutOn(_autoPayout);
}
function setFeeRateOnNFT(address payable _nft, uint256 _feeRate) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setFeeRate(_feeRate);
}
function setUnitsPerTransactionOnNFT(address payable _nft,uint256 _units) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setUnitsPerTransaction(_units);
}
function setMaxSupplyOnNFT(address payable _nft, uint256 _supply) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setMaxSupply(_supply);
}
function setDefaultTokenURIOnNFT(address payable _nft, string memory _tokenUri) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setDefaultTokenURI(_tokenUri);
}
function setPrizeTokenURIOnNFT(address payable _nft, string memory _tokenUri) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setPrizeTokenURI(_tokenUri);
}
function setArtistOnNFT(address payable _nft, address payable _artist) external onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.setArtist(_artist);
}
function beginBattleOnNFT(address payable _nft) external onlySupport {
BattleRoyale battle = BattleRoyale(_nft);
battle.beginBattle();
}
function executePayoutOnNFT(address payable _nft) public onlySupport payable {
BattleRoyale battle = BattleRoyale(_nft);
battle.executePayout();
}
/* ======== Battle Royale Methods ======== */
function transferContractOwnership(address payable newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
revokeAccessRole(payable(owner()));
grantSupportAccess(newOwner);
transferOwnership(newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./vendor/SafeMathChainlink.sol";
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 {
using SafeMathChainlink for uint256;
/**
* @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 constant private 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].add(1);
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* 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) public {
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.6.0 <0.9.0;
import "./ERC721Tradable.sol";
import "./AddressArray.sol";
import "./Uint256Array.sol";
import "./BattleRoyaleArena.sol";
contract BattleRoyale is ERC721Tradable {
using AddressArray for AddressArray.Addresses;
using Uint256Array for Uint256Array.Uint256s;
// Structure of token data on chain
struct NFTRoyale {
bool inPlay;
uint256 placement;
}
// Maximum number of mintable tokens
uint256 public maxSupply = 0;
// current purchasable units per transaction
uint256 public unitsPerTransaction;
// Prize token URI to be set to winner
string public prizeTokenURI;
// Prize token URI to be set to winner
string public defaultTokenURI;
// time in minutes
uint256 public intervalTime;
// timestamp of last elimination
uint256 public timestamp;
// initial price per token
uint256 public price;
// Current game state
enum BATTLE_STATE {
STANDBY,
RUNNING,
ENDED
}
BATTLE_STATE public battleState;
// Look into elimination logic and how to maintain state of all NFTs in and out of play
Uint256Array.Uint256s inPlay;
Uint256Array.Uint256s outOfPlay;
// Array of purchaser addresses
AddressArray.Addresses purchasers;
// Temp mapping for NFTs awaiting game execution
mapping(uint256 => NFTRoyale) public nftRoyales;
// set to true when wanting the game to start automatically once sales hit max supply
bool public autoStart;
// set to true when wanting the game to start automatically once sales hit max supply
bool public autoPayout;
// Address of the artist
address payable public artist;
address payable public delegate;
// Set rate
uint256 public feeRate;
/*
* constructor
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _price,
uint256 _units,
uint256 _supply,
bool _autoStart,
bool _autoPayout,
address payable _delegate
)
public ERC721Tradable(
_name,
_symbol,
'https://ipfs.io/ipfs/'
) {
battleState = BATTLE_STATE.STANDBY;
intervalTime = 30;
price = _price;
unitsPerTransaction = _units;
maxSupply = _supply;
autoStart = _autoStart;
autoPayout = _autoPayout;
delegate = _delegate;
}
/*
* Mint NFTs
*/
function purchase(uint256 units) external payable {
require(price > 0);
require(battleState == BATTLE_STATE.STANDBY);
require(maxSupply > 0 && totalSupply() < maxSupply);
require(units <= maxSupply - totalSupply());
require(units > 0 && units <= unitsPerTransaction);
require(bytes(defaultTokenURI).length > 0);
require(msg.value >= (price * units));
require(purchasers.getIndex(msg.sender) < 0, "Only 1 purchase per account.");
// add buyer address to list
purchasers.push(msg.sender);
for (uint256 i = 0; i < units; i++) {
uint256 tokenId = mintTo(msg.sender);
_setTokenURI(tokenId, defaultTokenURI);
inPlay.push(tokenId);
nftRoyales[tokenId] = NFTRoyale({
inPlay: true,
placement: 0
});
}
// Begin battle if max supply has been reached
if (maxSupply == totalSupply() && autoStart) {
startBattle();
}
}
/*
* Burn method
* @param {[type]} uint256 [description]
* @return {[type]} [description]
*/
function burn(uint256 _tokenId) public virtual {
require(msg.sender == ownerOf(_tokenId) || msg.sender == delegate || msg.sender == owner());
delete nftRoyales[_tokenId];
inPlay.remove(_tokenId);
_burn(_tokenId);
}
/* ==========================
* BATTLE ROYALE METHODS
* ========================== */
/*
* Method to withdraw ETH
*/
function withdraw(uint256 amount) external override virtual {
require(msg.sender == delegate || msg.sender == owner());
uint256 balance = address(this).balance;
require(amount <= balance);
if (delegate != address(0)) {
payable(delegate).transfer(amount);
} else {
msg.sender.transfer(amount);
}
}
/*
* Get Current ETH Balance from contract
*/
function getCurrentBalance() external override returns (uint256) {
require(msg.sender == delegate || msg.sender == owner());
uint256 balance = address(this).balance;
return balance;
}
/**
* get all token IDs In Play
* @return {[type]} array of IDs
*/
function getInPlay() external view returns (uint256[] memory) {
return inPlay.getAll();
}
function getInPlaySize() external view returns (uint256) {
return inPlay.size();
}
/**
* get all token IDs out of Play
* @return {[type]} array of IDs
*/
function getOutOfPlay() external view returns (uint256[] memory) {
return outOfPlay.getAll();
}
/*
* Set Interval
* @param {[type]} uint256 [description]
*/
function setIntervalTime(uint256 _intervalTime) external payable returns (uint256) {
require(msg.sender == delegate || msg.sender == owner());
intervalTime = _intervalTime;
}
/*
* isTokenInPlay - check if owner is still in player
*/
function isTokenInPlay(uint256 _tokenId) external view returns (bool) {
return nftRoyales[_tokenId].inPlay;
}
/*
* getTokenPlacement
*/
function getTokenPlacement(uint256 _tokenId) external view returns (uint256) {
return nftRoyales[_tokenId].placement;
}
/*
* set currentPrice
*/
function setPrice(uint256 _price) external payable {
require(msg.sender == delegate || msg.sender == owner());
price = _price;
}
/*
* Toggle auto-start on or off
*/
function autoStartOn(bool _autoStart) external payable {
require(msg.sender == delegate || msg.sender == owner());
autoStart = _autoStart;
}
/*
* Toggle auto-start on or off
*/
function autoPayoutOn(bool _autoPayout) external payable {
require(msg.sender == delegate || msg.sender == owner());
autoPayout = _autoPayout;
}
/*
* Set Fee Rate - aggreed rate the contract takes from the artist for initial sale
*/
function setFeeRate(uint256 _feeRate) external payable {
require(msg.sender == delegate || msg.sender == owner());
feeRate = _feeRate;
}
/*
* setUnitsPerTransaction
*/
function setUnitsPerTransaction(uint256 _units) external payable {
require(msg.sender == delegate || msg.sender == owner());
unitsPerTransaction = _units;
}
/*
* setMaxSupply
*/
function setMaxSupply(uint256 supply) external payable {
require(msg.sender == delegate || msg.sender == owner());
maxSupply = supply;
}
/*
* setdefaultTokenURI method to set the meta-data uri for the winning token to
* be set later when game has ended
* @param string IPFS meta-data uri
*/
function setDefaultTokenURI(string memory _tokenUri) external payable {
require(msg.sender == delegate || msg.sender == owner());
defaultTokenURI = _tokenUri;
}
/*
* setPrizeTokenURI method to set the meta-data uri for the winning token to
* be set later when game has ended
* @param string IPFS meta-data uri
*/
function setPrizeTokenURI(string memory _tokenUri) external payable {
require(msg.sender == delegate || msg.sender == owner());
prizeTokenURI = _tokenUri;
}
/*
* set artist
*/
function setArtist(address payable _artist) external payable {
require(msg.sender == delegate || msg.sender == owner());
artist = _artist;
}
/*
* Delegate notifier method
*/
function notifyGameEnded() internal {
BattleRoyaleArena arena = BattleRoyaleArena(payable(delegate));
arena.gameDidEnd(address(this));
}
/*
* getBattleState
* @return current state string of the game to web app
*/
function getBattleState() external view returns (string memory) {
if (battleState == BATTLE_STATE.STANDBY) {
return 'STANDBY';
}
if (battleState == BATTLE_STATE.RUNNING) {
return 'RUNNING';
}
if (battleState == BATTLE_STATE.ENDED) {
return 'ENDED';
}
}
function getBattleStateInt() external view returns (uint256) {
return uint256(battleState);
}
/*
* beginBattle
* Method to call to begin the game battle
*/
function beginBattle() external {
require(msg.sender == delegate || msg.sender == owner());
startBattle();
}
function startBattle() internal {
require(bytes(prizeTokenURI).length > 0 && inPlay.size() > 1);
battleState = BATTLE_STATE.RUNNING;
// Set to current clock
timestamp = block.timestamp;
}
/*
* executeRandomElimination trigger elimination using Chainlink VRF
*/
function executeRandomElimination(uint256 _randomNumber) external payable {
require(msg.sender == delegate || msg.sender == owner());
require(battleState == BATTLE_STATE.RUNNING);
require(inPlay.size() > 1);
uint256 i = _randomNumber % inPlay.size();
uint256 tokenId = inPlay.atIndex(i);
outOfPlay.push(tokenId);
inPlay.remove(tokenId);
NFTRoyale storage royale = nftRoyales[tokenId];
royale.inPlay = false;
royale.placement = inPlay.size() + 1;
timestamp = block.timestamp;
if (inPlay.size() == 1) {
battleState = BATTLE_STATE.ENDED;
royale = nftRoyales[tokenId];
royale.inPlay = false;
royale.placement = inPlay.size();
tokenId = inPlay.atIndex(0);
_setTokenURI(tokenId, prizeTokenURI);
notifyGameEnded();
if (autoPayout) {
executeAutoPayout();
}
}
}
/*
* calculateFee
* Uses basis points to calculate fee
*/
function calculateFee(uint amount) internal returns (uint) {
require((amount / 1000) * 1000 == amount, 'amount is too small');
return amount * feeRate / 10000;
}
/*
* payout artist
*/
function executePayout() public payable {
require(msg.sender == delegate || msg.sender == owner());
executeAutoPayout();
}
function executeAutoPayout() internal {
uint256 balance = address(this).balance;
if (artist != address(0)
&& (balance / 1000) * 1000 == balance
&& feeRate > 0) {
uint256 payout = balance - calculateFee(balance);
artist.transfer(payout);
}
balance = address(this).balance;
payable(delegate).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
library AddressArray {
using AddressArray for Addresses;
struct Addresses {
address payable[] _items;
}
/**
* @notice push an address to the array
* @dev if the address already exists, it will not be added again
* @param self Storage array containing address type variables
* @param element the element to add in the array
*/
function push(Addresses storage self, address payable element) internal returns (bool) {
if (!exists(self, element)) {
self._items.push(element);
return true;
}
return false;
}
/**
* @notice remove an address from the array
* @dev finds the element, swaps it with the last element, and then deletes it;
* returns a boolean whether the element was found and deleted
* @param self Storage array containing address type variables
* @param element the element to remove from the array
*/
function remove(Addresses storage self, address payable element) internal returns (bool) {
int256 i = getIndex(self, element);
if (i >= 0) {
return removeByIndex(self, uint256(i));
}
return false;
}
/**
* @notice get the address at a specific index from array
* @dev revert if the index is out of bounds
* @param self Storage array containing address type variables
* @param index the index in the array
*/
function atIndex(Addresses storage self, uint256 index) internal view returns (address payable) {
require(index < size(self), "the index is out of bounds");
return self._items[index];
}
/**
* @notice get the size of the array
* @param self Storage array containing address type variables
*/
function size(Addresses storage self) internal view returns (uint256) {
return self._items.length;
}
/**
* @notice check if an element exist in the array
* @param self Storage array containing address type variables
* @param element the element to check if it exists in the array
*/
function exists(Addresses storage self, address payable element) internal view returns (bool) {
return getIndex(self, element) >= 0;
}
/**
* @notice get the array
* @param self Storage array containing address type variables
*/
function getAll(Addresses storage self) internal view returns(address payable[] memory) {
return self._items;
}
/*
* @notice get index of address
* @param self Storage array containing address type variables
* @param element the element to get index in array
*/
function getIndex(Addresses storage self, address payable element) internal view returns(int256) {
for (uint256 i = 0; i < size(self); i++){
if(self._items[i] == element) {
return int256(i);
}
uint256 j = size(self) - 1 - i;
if (self._items[j] == element) {
return int256(j);
}
if (i >= j) {
break;
}
}
return -1;
}
/*
* @notice get index of address
* @param self Storage array containing address type variables
* @param i index of element to remove
*/
function removeByIndex(Addresses storage self, uint256 i) internal returns (bool) {
if (i < size(self)) {
uint last = size(self) - 1;
if (i < last) {
self._items[i] = self._items[last];
}
self._items.pop();
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./AddressArray.sol";
contract CustomAccessControl is AccessControl, Ownable {
using AddressArray for AddressArray.Addresses;
// Array of purchaser addresses
AddressArray.Addresses users;
bytes32 public constant SUPPORT_ROLE = keccak256("DEFAULT_SUPPORT_ROLE");
function supportLevelAccess(address account) public view returns (bool) {
return hasRole(SUPPORT_ROLE, account) || adminLevelAccess(account);
}
function adminLevelAccess(address account) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account) || account == owner();
}
function superAdminLevelAccess(address account) public view returns (bool) {
return account == owner();
}
function grantSupportAccess(address payable account) public onlyOwner {
if (users.exists(account)) {
revokeAccessRole(account);
} else {
users.push(account);
}
grantRole(SUPPORT_ROLE, account);
}
function grantAdminAccess(address payable account) public onlyOwner {
if (users.exists(account)) {
revokeAccessRole(account);
} else {
users.push(account);
}
grantRole(DEFAULT_ADMIN_ROLE, account);
}
function revokeAccessRole(address payable account) public payable onlyOwner returns (bool) {
if (hasRole(DEFAULT_ADMIN_ROLE, account)) {
revokeRole(DEFAULT_ADMIN_ROLE, account);
users.remove(account);
return true;
} else if (hasRole(SUPPORT_ROLE, account)) {
users.remove(account);
revokeRole(SUPPORT_ROLE, account);
return true;
}
return false;
}
function getAddressRole(address account) external returns (string memory) {
if (hasRole(DEFAULT_ADMIN_ROLE, account)) {
return 'ADMIN_ROLE';
} else if (hasRole(SUPPORT_ROLE, account)) {
return 'SUPPORT_ROLE';
}
return 'UNASSIGNED';
}
function getAllAccessAddresses() external view onlyOwner returns(address payable[] memory) {
return users.getAll();
}
function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlySupport() {
require(supportLevelAccess(_msgSender()), "Caller does not have access");
_;
}
modifier onlyAdmin() {
require(adminLevelAccess(_msgSender()), "Caller does not have access");
_;
}
}
// 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 SafeMathChainlink {
/**
* @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");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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
pragma solidity ^0.6.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.6.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
contract ERC721Tradable is ERC721, Ownable {
using Strings for string;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI
) public ERC721(_name, _symbol) {
_setBaseURI(_baseURI);
}
/**
* Fallback function to receive ETH
*/
receive() external payable {}
/*
* Method to withdraw ETH
*/
function withdraw(uint256 amount) external virtual onlyOwner {
uint256 balance = address(this).balance;
require(amount <= balance);
msg.sender.transfer(amount);
}
/*
* Get Current ETH Balance from contract
*/
function getCurrentBalance() external virtual onlyOwner returns (uint256) {
uint256 balance = address(this).balance;
return balance;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) internal returns (uint256) {
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
_safeMint(_to, newTokenId);
return newTokenId;
}
/*
* setTokenURI
* @param {[type]} uint256 [description]
* @param {[type]} string [description]
*/
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner payable {
_setTokenURI(_tokenId, _tokenURI);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
library Uint256Array {
using Uint256Array for Uint256s;
struct Uint256s {
uint256[] _items;
}
/**
* @notice push an uint256 to the array
* @dev if the uint256 already exists, it will not be added again
* @param self Storage array containing uint256 type variables
* @param element the element to add in the array
*/
function push(Uint256s storage self, uint256 element) internal returns (bool) {
if (!exists(self, element)) {
self._items.push(element);
return true;
}
return false;
}
/**
* @notice remove a uint256 from the array
* @dev finds the element, swaps it with the last element, and then deletes it;
* returns a boolean whether the element was found and deleted
* @param self Storage array containing uint256 type variables
* @param element the element to remove from the array
*/
function remove(Uint256s storage self, uint256 element) internal returns (bool) {
int256 i = getIndex(self, element);
if (i >= 0) {
return removeByIndex(self, uint256(i));
}
return false;
}
/**
* @notice get the uint256 at a specific index from array
* @dev revert if the index is out of bounds
* @param self Storage array containing uint256 type variables
* @param index the index in the array
*/
function atIndex(Uint256s storage self, uint256 index) internal view returns (uint256) {
require(index < size(self), "the index is out of bounds");
return self._items[index];
}
/**
* @notice get the size of the array
* @param self Storage array containing uint256 type variables
*/
function size(Uint256s storage self) internal view returns (uint256) {
return self._items.length;
}
/**
* @notice check if an element exist in the array
* @param self Storage array containing uint256 type variables
* @param element the element to check if it exists in the array
*/
function exists(Uint256s storage self, uint256 element) internal view returns (bool) {
return getIndex(self, element) >= 0;
}
/**
* @notice get the array
* @param self Storage array containing uint256 type variables
*/
function getAll(Uint256s storage self) internal view returns(uint256[] memory) {
return self._items;
}
/*
* @notice get index of uint256
* @param self Storage array containing uint256 type variables
* @param element the element to get index in array
*/
function getIndex(Uint256s storage self, uint256 element) internal view returns(int256) {
for (uint256 i = 0; i < size(self); i++){
if(self._items[i] == element) {
return int256(i);
}
uint256 j = size(self) - 1 - i;
if (self._items[j] == element) {
return int256(j);
}
if (i >= j) {
break;
}
}
return -1;
}
/*
* @notice get index of uint256
* @param self Storage array containing uint256 type variables
* @param i index of element to remove
*/
function removeByIndex(Uint256s storage self, uint256 i) internal returns (bool) {
if (i < size(self)) {
uint last = size(self) - 1;
if (i < last) {
self._items[i] = self._items[last];
}
self._items.pop();
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal 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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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.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;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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());
}
}
}
|
Burn method {[type]} uint256 [description] return {[type]} [description]/
|
function burn(uint256 _tokenId) public virtual {
require(msg.sender == ownerOf(_tokenId) || msg.sender == delegate || msg.sender == owner());
delete nftRoyales[_tokenId];
inPlay.remove(_tokenId);
_burn(_tokenId);
}
| 1,384,337
|
./full_match/43114/0x9Fefb85d4eB2DF59923C6102c4801718E6415179/sources/contracts/3_Ballot.sol
|
Return reward multiplier over the given _from to _to block. View function to see pending CAKEs on frontend. Deposit LP tokens to MasterChef for CAKE allocation. Withdraw LP tokens from MasterChef. Stake CAKE tokens to MasterChef Withdraw CAKE tokens from STAKING. Withdraw without caring about rewards. EMERGENCY ONLY.
|
interface IPancakeswapFarm {
function poolLength() external view returns (uint256);
function userInfo() external view returns (uint256);
function getMultiplier(uint256 _from, uint256 _to)
external
view
returns (uint256);
function pendingCake(uint256 _pid, address _user)
external
view
returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function enterStaking(uint256 _amount) external;
function leaveStaking(uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
}
| 4,562,732
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IUniswapV3Batcher {
event Minted(uint256 tokenId);
event Collected(uint256 tokenId, uint256 amount0, uint256 amount1);
event Closed(uint256 tokenId, uint256 amount0, uint256 amount1);
event FeeSet(uint256 oldFee, uint256 newFee);
/// @notice Collect fees from owned NFTs
/// @dev Call this to save gas on collecting from LPs individually. Note that this contract has to
/// be approved by `msg.sender` preferably using `setApprovalForAll`
/// @param tokenIds The ids of the tokens to collect fees from
function collect(uint256[] calldata tokenIds) external payable;
struct CollectParams {
uint256 tokenId;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
bool shouldClose;
bool shouldBurn;
}
/// @notice Removes all liquidity, and collects owed fees
/// @dev Call this to close multiple LPs of all liquidity. Is more efficient than closing one LP at a time
/// and NFTs can be burnt if necessary. Note that this contract has to
/// be approved by `msg.sender` preferably using `setApprovalForAll`
/// @param params The ids of the tokens with slippage tolerances encoded as `CollectParams` calldata
function collectAndClose(CollectParams[] calldata params) external payable;
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 deadline;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
}
struct BalanceParams {
address token;
uint256 amount;
}
/// @notice Mints a new NFT position
/// @dev Call this to open multiple LPs on various pools. Is more efficient than opening one LP at a time
/// Note that this contract must be approved for all tokens by `msg.sender` and all minted positions
/// are created with the recipient to be `msg.sender`
/// @param params The params necessary to open positions encoded as `MintParams` in calldata
/// @param balances The balances necessary of each token to mint the positions encoded as `BalanceParams` in calldata
/// @return tokenIds The NF token Ids of the minted positions
function mint(MintParams[] calldata params, BalanceParams[] calldata balances) external payable returns (uint256[] memory tokenIds);
/// @notice Helper function to close and mint new LP
/// @dev Call this to close multiple LPs, then open multiple LPs on various pools. Is more efficient than closeing/opening one LP at a time
/// Note that this contract must be approved for all tokens by `msg.sender` and all minted positions
/// are created with the recipient to be `msg.sender`. NFTs need to be approved for `msg.sender` preferably using `setApprovalForAll`
/// @param mintParams The params necessary to open positions encoded as `MintParams` in calldata
/// @param balances The balances necessary of each token to mint the positions encoded as `BalanceParams` in calldata
/// @param collectParams The tokens to close the position encoded as `CollectParams` in calldata
/// @return tokenIds The NF token Ids of the newly minted positions
function rerange(MintParams[] calldata mintParams, BalanceParams[] calldata balances, CollectParams[] calldata collectParams) external payable returns (uint256[] memory tokenIds);
/// @notice Sets base fee for using manager
/// @dev Has onlyOwner modifier
/// @param newFee New fee to set denominated in wei
function setFee(uint256 newFee) external;
/// @notice Withdraws fees to address
/// @dev Has onlyOwner modifier
/// @param usr Address to send ETH
function withdraw(address usr) external;
}
|
Removes all liquidity, and collects owed fees Call this to close multiple LPs of all liquidity. Is more efficient than closing one LP at a time and NFTs can be burnt if necessary. Note that this contract has to be approved by `msg.sender` preferably using `setApprovalForAll` params The ids of the tokens with slippage tolerances encoded as `CollectParams` calldata
|
function collectAndClose(CollectParams[] calldata params) external payable;
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 deadline;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
}
| 1,040,952
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract DeScratchOff is VRFConsumerBase, ERC721URIStorage{
bytes32 internal keyHash;
uint256 internal fee;
using Counters for Counters.Counter;
Counters.Counter public _tokenIds;
uint256 public randomResult;
uint public scratchCardSupply = 0;
uint public artistCardTotal = 0;
mapping(uint => ScratchCard) public scratchCards;
mapping(uint => ArtistCard) public artistCards;
struct ScratchCard {
uint id;
uint artistCardId;
uint[] numbers;
bool isScratch;
address owner;
}
struct ArtistCard {
uint id;
string coverPhotoCid;
string imagesCid;
address artist;
}
event ScratchCardPurchase (
uint id,
uint artistCardId,
uint[] numbers,
bool isScratch,
address owner
);
event ScratchCardCreated (
uint id,
string coverPhotoCid,
string imagesCid,
address artist
);
/**
* Constructor inherits VRFConsumerBase
*
* Network: Polygon (Matic) Mumbai Testnet
* Chainlink VRF Coordinator address: 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
* LINK token address: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
* Key Hash: 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4
*/
constructor ()
VRFConsumerBase(
0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, // VRF Coordinator
0x326C977E6efc84E512bB9C30f76E30c160eD06FB // LINK Token
)
ERC721("De-Scratch Card", "DSC")
{
keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4;
fee = 0.0001 * 10 ** 18; // 0.0001 LINK
}
/**
* Create a Scratch Card
*/
function createScratchCard(string memory _coverPhotoCid, string memory _imagesCid) external {
artistCardTotal++;
artistCards[artistCardTotal] = ArtistCard(artistCardTotal, _coverPhotoCid, _imagesCid, msg.sender);
emit ScratchCardCreated(artistCardTotal, _coverPhotoCid, _imagesCid, msg.sender);
}
/**
* Buy a Scratch Card NFT
*/
function buyScratchCard(uint _artistCardId) external {
ArtistCard storage _artistCards = artistCards[_artistCardId];
scratchCardSupply++;
_tokenIds.increment();
uint _tokenId = _tokenIds.current();
_safeMint(msg.sender, _tokenId);
_setTokenURI(_tokenId, _artistCards.coverPhotoCid);
scratchCards[scratchCardSupply] = ScratchCard(scratchCardSupply, _artistCardId, new uint[](0), false, msg.sender);
emit ScratchCardPurchase(scratchCardSupply, _artistCardId, new uint[](0), false, msg.sender);
}
/**
* Get numbers on Scratch Card
*/
function getNumbersByScratchCard(uint _id) public view returns (uint [] memory){
ScratchCard storage _scratchCard = scratchCards[_id];
return _scratchCard.numbers;
}
/**
* Set list of random numbers on Scratch Card
*/
function fillScratchCard(uint _id) external {
ScratchCard storage _scratchCard = scratchCards[_id];
require(_scratchCard.isScratch == false, "You already use this Scratch Card");
_scratchCard.isScratch = true;
getRandomNumber();
for(uint i = 0; i < 9; i++){
uint256 _randomNumber = uint256(keccak256(abi.encode(randomResult, i))) % 8 + 1; // 0 - 9
_scratchCard.numbers.push(_randomNumber);
}
}
/**
* Requests randomness
*/
function getRandomNumber() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) > fee, "Not enough LINK - fill contract with faucet");
return requestRandomness(keyHash, fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
bytes32 i = requestId;
i = requestId;
randomResult = randomness;
}
/**
* DO NOT ADD THIS IN PRODUCTION
* Avoid locking your LINK in the contract
*/
function withdrawLink() external {
require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "Unable to transfer");
}
}
|
Get numbers on Scratch Card/
|
function getNumbersByScratchCard(uint _id) public view returns (uint [] memory){
ScratchCard storage _scratchCard = scratchCards[_id];
return _scratchCard.numbers;
}
| 5,458,830
|
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
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 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;
}
}
// File: contracts/access/Operator.sol
pragma solidity >=0.7.0 <0.8.0;
abstract contract Operator is Context, Ownable {
address private _operator;
event OperatorTransferred(
address indexed previousOperator,
address indexed newOperator
);
constructor() {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
}
function operator() public view returns (address) {
return _operator;
}
modifier onlyOperator() {
require(
_operator == _msgSender(),
'operator: caller is not the operator'
);
_;
}
function isOperator() public view returns (bool) {
return _msgSender() == _operator;
}
function transferOperator(address newOperator_) public onlyOwner {
_transferOperator(newOperator_);
}
function _transferOperator(address newOperator_) internal {
require(
newOperator_ != address(0),
'operator: zero address given for new operator'
);
emit OperatorTransferred(address(0), newOperator_);
_operator = newOperator_;
}
}
// File: @openzeppelin/contracts/math/Math.sol
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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/distribution/PoolStore.sol
pragma solidity >=0.7.0 <0.8.0;
interface IPoolStore {
/* ================= EVENTS ================= */
event Deposit(
address indexed operator,
address indexed owner,
uint256 indexed pid,
uint256 amount
);
event Withdraw(
address indexed operator,
address indexed owner,
uint256 indexed pid,
uint256 amount
);
/* ================= CALLS ================= */
// common
function totalWeight() external view returns (uint256);
function poolLength() external view returns (uint256);
// index
function poolIdsOf(address _token) external view returns (uint256[] memory);
// pool info
function nameOf(uint256 _pid) external view returns (string memory);
function tokenOf(uint256 _pid) external view returns (address);
function weightOf(uint256 _pid) external view returns (uint256);
function totalSupply(uint256 _pid) external view returns (uint256);
function balanceOf(uint256 _pid, address _owner)
external
view
returns (uint256);
/* ================= TXNS ================= */
function deposit(
uint256 _pid,
address _owner,
uint256 _amount
) external;
function withdraw(
uint256 _pid,
address _owner,
uint256 _amount
) external;
function emergencyWithdraw(uint256 _pid) external;
}
interface IPoolStoreGov {
/* ================= EVENTS ================= */
event EmergencyReported(address indexed reporter);
event EmergencyResolved(address indexed resolver);
event WeightFeederChanged(
address indexed operator,
address indexed oldFeeder,
address indexed newFeeder
);
event PoolAdded(
address indexed operator,
uint256 indexed pid,
string name,
address token,
uint256 weight
);
event PoolWeightChanged(
address indexed operator,
uint256 indexed pid,
uint256 from,
uint256 to
);
event PoolNameChanged(
address indexed operator,
uint256 indexed pid,
string from,
string to
);
/* ================= TXNS ================= */
// emergency
function reportEmergency() external;
function resolveEmergency() external;
// feeder
function setWeightFeeder(address _newFeeder) external;
// pool setting
function addPool(
string memory _name,
IERC20 _token,
uint256 _weight
) external;
function setPool(uint256 _pid, uint256 _weight) external;
function setPool(uint256 _pid, string memory _name) external;
}
contract PoolStore is IPoolStore, IPoolStoreGov, Operator {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ================= DATA STRUCTURE ================= */
struct Pool {
string name;
IERC20 token;
uint256 weight;
uint256 totalSupply;
}
/* ================= STATES ================= */
uint256 public override totalWeight = 0;
Pool[] public pools;
mapping(uint256 => mapping(address => uint256)) balances;
mapping(address => uint256[]) public indexByToken;
bool public emergency = false;
address public weightFeeder;
constructor() Operator() {
weightFeeder = _msgSender();
}
/* ================= GOV - OWNER ONLY ================= */
/**
* @dev CAUTION: DO NOT USE IN NORMAL SITUATION
* @notice Enable emergency withdraw
*/
function reportEmergency() public override onlyOwner {
emergency = true;
emit EmergencyReported(_msgSender());
}
/**
* @dev CAUTION: DO NOT USE IN NORMAL SITUATION
* @notice Disable emergency withdraw
*/
function resolveEmergency() public override onlyOwner {
emergency = false;
emit EmergencyResolved(_msgSender());
}
/*
* @param _newFeeder weight feeder address to change
*/
function setWeightFeeder(address _newFeeder) public override onlyOwner {
address oldFeeder = weightFeeder;
weightFeeder = _newFeeder;
emit WeightFeederChanged(_msgSender(), oldFeeder, _newFeeder);
}
/**
* @param _token pool token
* @param _weight pool weight
*/
function addPool(
string memory _name,
IERC20 _token,
uint256 _weight
) public override onlyOwner {
totalWeight = totalWeight.add(_weight);
uint256 index = pools.length;
indexByToken[address(_token)].push(index);
pools.push(
Pool({name: _name, token: _token, weight: _weight, totalSupply: 0})
);
emit PoolAdded(_msgSender(), index, _name, address(_token), _weight);
}
/**
* @param _pid pool id
* @param _weight target pool weight
*/
function setPool(uint256 _pid, uint256 _weight)
public
override
onlyWeightFeeder
checkPoolId(_pid)
{
Pool memory pool = pools[_pid];
uint256 oldWeight = pool.weight;
totalWeight = totalWeight.add(_weight).sub(pool.weight);
pool.weight = _weight;
pools[_pid] = pool;
emit PoolWeightChanged(_msgSender(), _pid, oldWeight, _weight);
}
/**
* @param _pid pool id
* @param _name name of pool
*/
function setPool(uint256 _pid, string memory _name)
public
override
checkPoolId(_pid)
onlyOwner
{
string memory oldName = pools[_pid].name;
pools[_pid].name = _name;
emit PoolNameChanged(_msgSender(), _pid, oldName, _name);
}
/* ================= MODIFIER ================= */
modifier onlyWeightFeeder {
require(_msgSender() == weightFeeder, 'PoolStore: unauthorized');
_;
}
modifier checkPoolId(uint256 _pid) {
require(_pid <= pools.length, 'PoolStore: invalid pid');
_;
}
/* ================= CALLS - ANYONE ================= */
/**
* @return total pool length
*/
function poolLength() public view override returns (uint256) {
return pools.length;
}
/**
* @param _token pool token address
* @return pool id
*/
function poolIdsOf(address _token)
public
view
override
returns (uint256[] memory)
{
return indexByToken[_token];
}
/**
* @param _pid pool id
* @return name of pool
*/
function nameOf(uint256 _pid)
public
view
override
checkPoolId(_pid)
returns (string memory)
{
return pools[_pid].name;
}
/**
* @param _pid pool id
* @return pool token
*/
function tokenOf(uint256 _pid)
public
view
override
checkPoolId(_pid)
returns (address)
{
return address(pools[_pid].token);
}
/**
* @param _pid pool id
* @return pool weight
*/
function weightOf(uint256 _pid)
public
view
override
checkPoolId(_pid)
returns (uint256)
{
return pools[_pid].weight;
}
/**
* @param _pid pool id
* @return total staked token amount
*/
function totalSupply(uint256 _pid)
public
view
override
checkPoolId(_pid)
returns (uint256)
{
return pools[_pid].totalSupply;
}
/**
* @param _pid pool id
* @param _sender staker address
* @return staked amount of user
*/
function balanceOf(uint256 _pid, address _sender)
public
view
override
checkPoolId(_pid)
returns (uint256)
{
return balances[_pid][_sender];
}
/* ================= TXNS - OPERATOR ONLY ================= */
/**
* @param _pid pool id
* @param _owner stake address
* @param _amount stake amount
*/
function deposit(
uint256 _pid,
address _owner,
uint256 _amount
) public override checkPoolId(_pid) onlyOperator {
pools[_pid].totalSupply = pools[_pid].totalSupply.add(_amount);
balances[_pid][_owner] = balances[_pid][_owner].add(_amount);
IERC20(tokenOf(_pid)).safeTransferFrom(
_msgSender(),
address(this),
_amount
);
emit Deposit(_msgSender(), _owner, _pid, _amount);
}
function _withdraw(
uint256 _pid,
address _owner,
uint256 _amount
) internal {
pools[_pid].totalSupply = pools[_pid].totalSupply.sub(_amount);
balances[_pid][_owner] = balances[_pid][_owner].sub(_amount);
IERC20(tokenOf(_pid)).safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _owner, _pid, _amount);
}
/**
* @param _pid pool id
* @param _owner stake address
* @param _amount stake amount
*/
function withdraw(
uint256 _pid,
address _owner,
uint256 _amount
) public override checkPoolId(_pid) onlyOperator {
_withdraw(_pid, _owner, _amount);
}
/**
* @notice Anyone can withdraw its balance even if is not the operator
* @param _pid pool id
*/
function emergencyWithdraw(uint256 _pid) public override checkPoolId(_pid) {
require(emergency, 'PoolStore: not in emergency');
_withdraw(_pid, msg.sender, balanceOf(_pid, _msgSender()));
}
}
// File: contracts/distribution/PoolStoreWrapper.sol
pragma solidity >=0.7.0 <0.8.0;
abstract contract PoolStoreWrapper is Context {
using SafeERC20 for IERC20;
IPoolStore public store;
function deposit(uint256 _pid, uint256 _amount) public virtual {
IERC20(store.tokenOf(_pid)).safeTransferFrom(
_msgSender(),
address(this),
_amount
);
store.deposit(_pid, _msgSender(), _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public virtual {
store.withdraw(_pid, _msgSender(), _amount);
IERC20(store.tokenOf(_pid)).safeTransfer(_msgSender(), _amount);
}
}
// File: contracts/distribution/IPool.sol
pragma solidity >=0.7.0 <0.8.0;
interface IPool {
/* ================= EVENTS ================= */
event DepositToken(
address indexed owner,
uint256 indexed pid,
uint256 amount
);
event WithdrawToken(
address indexed owner,
uint256 indexed pid,
uint256 amount
);
event RewardClaimed(
address indexed owner,
uint256 indexed pid,
uint256 amount
);
/* ================= CALLS ================= */
function tokenOf(uint256 _pid) external view returns (address);
function poolIdsOf(address _token) external view returns (uint256[] memory);
function totalSupply(uint256 _pid) external view returns (uint256);
function balanceOf(uint256 _pid, address _owner)
external
view
returns (uint256);
function rewardRatePerPool(uint256 _pid) external view returns (uint256);
function rewardPerToken(uint256 _pid) external view returns (uint256);
function rewardEarned(uint256 _pid, address _target)
external
view
returns (uint256);
/* ================= TXNS ================= */
function massUpdate(uint256[] memory _pids) external;
function update(uint256 _pid) external;
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function claimReward(uint256 _pid) external;
function exit(uint256 _pid) external;
}
interface IPoolGov {
/* ================= EVENTS ================= */
event RewardNotified(
address indexed operator,
uint256 amount,
uint256 period
);
/* ================= TXNS ================= */
function setPeriod(uint256 _startTime, uint256 _period) external;
function setReward(uint256 _amount) external;
function setExtraRewardRate(uint256 _extra) external;
function stop() external;
function migrate(address _newPool, uint256 _amount) external;
}
// File: contracts/distribution/DistributionV2.sol
pragma solidity >=0.7.0 <0.8.0;
contract DistributionV2 is IPool, IPoolGov, PoolStoreWrapper, Operator {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ================= DATA STRUCTURE ================= */
struct User {
uint256 amount;
uint256 reward;
uint256 rewardPerTokenPaid;
}
struct Pool {
bool initialized;
uint256 rewardRate;
uint256 lastUpdateTime;
uint256 rewardPerTokenStored;
}
/* ================= STATE VARIABLES ================= */
// share
address public share;
mapping(address => bool) public approvals;
// poolId => Pool
mapping(uint256 => Pool) public pools;
// poolId => sender => User
mapping(uint256 => mapping(address => User)) public users;
// poolId => sender => bool
mapping(uint256 => mapping(address => bool)) public oldPoolClaimed;
address oldPool;
bool public stopped = false;
uint256 public rewardRate = 0;
uint256 public rewardRateExtra = 0;
// halving
uint256 public rewardRateBeforeHalve = 0;
// year2=>4%, year3=>3.5%, year4=>3%
uint256[] public inflationRate = [0, 0, 400, 350, 300];
uint256 public year = 1;
uint256 public startSupply = 860210511822372000000000;
// control
uint256 public period = 0;
uint256 public periodFinish = 0;
uint256 public startTime = 0;
/* ================= CONSTRUCTOR ================= */
constructor(address _share, address _poolStore) Ownable() {
share = _share;
store = IPoolStore(_poolStore);
}
/* ================= GOV - OWNER ONLY ================= */
/**
* @param _startTime starting time to distribute
* @param _period distribution period
*/
function setPeriod(uint256 _startTime, uint256 _period)
public
override
onlyOperator
{
// re-calc
if (startTime <= block.timestamp && block.timestamp < periodFinish) {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = leftover.div(_period);
}
period = _period;
startTime = _startTime;
periodFinish = _startTime.add(_period);
}
/**
* @param _amount token amount to distribute
*/
function setReward(uint256 _amount) public override onlyOperator {
require(block.timestamp < periodFinish, 'BACPool: already finished');
if (startTime <= block.timestamp) {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = _amount.add(leftover).div(
periodFinish.sub(block.timestamp)
);
} else {
rewardRate = rewardRate.add(
_amount.div(periodFinish.sub(startTime))
);
}
}
function setExtraRewardRate(uint256 _extra) public override onlyOwner {
rewardRateExtra = _extra;
}
function setOldPool(address _oldPool) public onlyOwner {
oldPool = _oldPool;
}
/**
* @dev STOP DISTRIBUTION
*/
function stop() public override onlyOwner {
periodFinish = block.timestamp;
stopped = true;
}
/**
* @dev MUST UPDATE ALL POOL REWARD BEFORE MIGRATION!!!!!
* @param _newPool new pool address to migrate
*/
function migrate(address _newPool, uint256 _amount)
public
override
onlyOwner
{
require(stopped, 'BACPool: not stopped');
IERC20(share).safeTransfer(_newPool, _amount);
uint256 remaining = startTime.add(period).sub(periodFinish);
uint256 leftover = remaining.mul(rewardRate);
IPoolGov(_newPool).setPeriod(block.timestamp.add(1), remaining);
IPoolGov(_newPool).setReward(leftover);
}
/* ================= MODIFIER ================= */
/**
* @param _pid pool id
* @param _target update target. if is empty, skip individual update.
*/
modifier updateReward(uint256 _pid, address _target) {
if (!approvals[store.tokenOf(_pid)]) {
IERC20(store.tokenOf(_pid)).safeApprove(
address(store),
type(uint256).max
);
approvals[store.tokenOf(_pid)] = true;
}
if (block.timestamp >= startTime) {
if (!pools[_pid].initialized) {
pools[_pid] = Pool({
initialized: true,
rewardRate: rewardRate,
lastUpdateTime: startTime,
rewardPerTokenStored: 0
});
}
// halve
if (!stopped && block.timestamp >= periodFinish) {
// 11% weekly decrease reward rate
if (block.timestamp < 1638144000) {
// 2021-11-29 00:00:00 UTC
rewardRateBeforeHalve = rewardRate;
rewardRate = rewardRate.mul(89).div(100);
} else {
period = 365 days;
year += 1;
uint256 periodAll =
startSupply.mul(inflationRate[year]).div(10000);
rewardRate = periodAll.div(31536000);
rewardRateBeforeHalve = rewardRate;
startSupply += periodAll;
// 2% for the year5 and beyond
inflationRate.push(200);
}
// set period
startTime = block.timestamp;
periodFinish = block.timestamp.add(period);
}
Pool memory pool = pools[_pid];
pool.rewardPerTokenStored = rewardPerToken(_pid);
if (pool.rewardRate == rewardRateBeforeHalve) {
pool.rewardRate = rewardRate;
}
pool.lastUpdateTime = applicableRewardTime();
pools[_pid] = pool;
if (_target != address(0x0)) {
User memory user = users[_pid][_target];
user.reward = rewardEarned(_pid, _target);
if (!oldPoolClaimed[_pid][_target]) {
oldPoolClaimed[_pid][_target] = true;
}
user.rewardPerTokenPaid = pool.rewardPerTokenStored;
users[_pid][_target] = user;
}
}
_;
}
/* ================= CALLS - ANYONE ================= */
/**
* @param _pid pool id
* @return pool token address
*/
function tokenOf(uint256 _pid) external view override returns (address) {
return store.tokenOf(_pid);
}
/**
* @param _token pool token address
* @return pool id
*/
function poolIdsOf(address _token)
external
view
override
returns (uint256[] memory)
{
return store.poolIdsOf(_token);
}
/**
* @param _pid pool id
* @return pool's total staked amount
*/
function totalSupply(uint256 _pid)
external
view
override
returns (uint256)
{
return store.totalSupply(_pid);
}
/**
* @param _owner staker address
* @return staker balance
*/
function balanceOf(uint256 _pid, address _owner)
external
view
override
returns (uint256)
{
return store.balanceOf(_pid, _owner);
}
/**
* @return applicable reward time
*/
function applicableRewardTime() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
/**
* @param _pid pool id
* @param _crit reward rate
*/
function _rewardRatePerPool(uint256 _pid, uint256 _crit)
internal
view
returns (uint256)
{
return _crit.mul(store.weightOf(_pid)).div(store.totalWeight());
}
/**
* @param _pid pool id
* @return calculated reward rate per pool
*/
function rewardRatePerPool(uint256 _pid)
public
view
override
returns (uint256)
{
return _rewardRatePerPool(_pid, rewardRate.add(rewardRateExtra));
}
/**
* @param _pid pool id
* @return RPT per pool
*/
function rewardPerToken(uint256 _pid)
public
view
override
returns (uint256)
{
Pool memory pool = pools[_pid];
if (store.totalSupply(_pid) == 0 || block.timestamp < startTime) {
return pool.rewardPerTokenStored;
}
if (pool.rewardRate != 0 && pool.rewardRate == rewardRateBeforeHalve) {
uint256 beforeHalve =
startTime
.sub(pool.lastUpdateTime)
.mul(_rewardRatePerPool(_pid, rewardRateBeforeHalve))
.mul(1e18)
.div(store.totalSupply(_pid));
uint256 afterHalve =
applicableRewardTime()
.sub(startTime)
.mul(rewardRatePerPool(_pid))
.mul(1e18)
.div(store.totalSupply(_pid));
return pool.rewardPerTokenStored.add(beforeHalve).add(afterHalve);
} else {
return
pool.rewardPerTokenStored.add(
applicableRewardTime()
.sub(pool.lastUpdateTime)
.mul(rewardRatePerPool(_pid))
.mul(1e18)
.div(store.totalSupply(_pid))
);
}
}
/**
* @param _pid pool id
* @param _target target address
* @return reward amount per pool
*/
function rewardEarned(uint256 _pid, address _target)
public
view
override
returns (uint256)
{
User memory user = users[_pid][_target];
uint256 oldUnclaim = 0;
if (oldPool != address(0x0) && !oldPoolClaimed[_pid][_target]) {
oldUnclaim += IPool(oldPool).rewardEarned(_pid, _target);
}
return
store
.balanceOf(_pid, _target)
.mul(rewardPerToken(_pid).sub(user.rewardPerTokenPaid))
.div(1e18)
.add(user.reward)
.add(oldUnclaim);
}
/* ================= TXNS - ANYONE ================= */
/**
* @param _pids array of pool ids
*/
function massUpdate(uint256[] memory _pids) public override {
for (uint256 i = 0; i < _pids.length; i++) {
update(_pids[i]);
}
}
/**
* @param _pid pool id
*/
function update(uint256 _pid)
public
override
updateReward(_pid, address(0x0))
{}
/**
* @param _pid pool id
* @param _amount deposit amount
*/
function deposit(uint256 _pid, uint256 _amount)
public
override(IPool, PoolStoreWrapper)
updateReward(_pid, _msgSender())
{
require(!stopped, 'BASPool: stopped');
super.deposit(_pid, _amount);
emit DepositToken(_msgSender(), _pid, _amount);
}
/**
* @param _pid pool id
* @param _amount withdraw amount
*/
function withdraw(uint256 _pid, uint256 _amount)
public
override(IPool, PoolStoreWrapper)
updateReward(_pid, _msgSender())
{
require(!stopped, 'BASPool: stopped');
super.withdraw(_pid, _amount);
emit WithdrawToken(_msgSender(), _pid, _amount);
}
/**
* @param _pid pool id
*/
function claimReward(uint256 _pid)
public
override
updateReward(_pid, _msgSender())
{
claimReward(_pid, _msgSender());
}
/**
* @param _pid pool id
* @param _owner claim for owner
*/
function claimReward(uint256 _pid, address _owner)
public
updateReward(_pid, _owner)
{
uint256 reward = users[_pid][_owner].reward;
if (reward > 0) {
users[_pid][_owner].reward = 0;
IERC20(share).safeTransfer(_owner, reward);
emit RewardClaimed(_owner, _pid, reward);
}
}
/**
* @dev withdraw + claim
* @param _pid pool id
*/
function exit(uint256 _pid) external override {
withdraw(_pid, store.balanceOf(_pid, _msgSender()));
claimReward(_pid);
}
}
|
_pid pool id return pool token/
|
function tokenOf(uint256 _pid)
public
view
override
checkPoolId(_pid)
returns (address)
{
return address(pools[_pid].token);
}
| 6,233,821
|
/**
*Submitted for verification at Etherscan.io on 2021-04-09
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
abstract contract IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external virtual view returns (address pair);
function allPairs(uint) external virtual view returns (address pair);
function allPairsLength() external virtual view returns (uint);
function feeTo() external virtual view returns (address);
function feeToSetter() external virtual view returns (address);
}
abstract contract IUniswapRouter {
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
virtual
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external virtual returns (uint256 amountA, uint256 amountB);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual returns (uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] memory path)
public
view
virtual
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] memory path)
public
view
virtual
returns (uint256[] memory amounts);
}
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
abstract contract IWETH {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(
address,
address,
uint256
) public virtual returns (bool);
function deposit() public payable virtual;
function withdraw(uint256) public virtual;
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// 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);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 Edited so it always first approves 0 and then the value, because of non standard tokens
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, 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,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library TokenUtils {
using SafeERC20 for IERC20;
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function approveToken(
address _tokenAddr,
address _to,
uint256 _amount
) internal {
if (_tokenAddr == ETH_ADDR) return;
if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
IERC20(_tokenAddr).safeApprove(_to, _amount);
}
}
function pullTokensIfNeeded(
address _token,
address _from,
uint256 _amount
) internal returns (uint256) {
// handle max uint amount
if (_amount == type(uint256).max) {
uint256 userAllowance = IERC20(_token).allowance(_from, address(this));
uint256 balance = getBalance(_token, _from);
// pull max allowance amount if balance is bigger than allowance
_amount = (balance > userAllowance) ? userAllowance : balance;
}
if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) {
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
return _amount;
}
function withdrawTokens(
address _token,
address _to,
uint256 _amount
) internal returns (uint256) {
if (_amount == type(uint256).max) {
_amount = getBalance(_token, address(this));
}
if (_to != address(0) && _to != address(this) && _amount != 0) {
if (_token != ETH_ADDR) {
IERC20(_token).safeTransfer(_to, _amount);
} else {
payable(_to).transfer(_amount);
}
}
return _amount;
}
function depositWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).deposit{value: _amount}();
}
function withdrawWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).withdraw(_amount);
}
function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) {
if (_tokenAddr == ETH_ADDR) {
return _acc.balance;
} else {
return IERC20(_tokenAddr).balanceOf(_acc);
}
}
function getTokenDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return IERC20(_token).decimals();
}
}
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
/// @title A stateful contract that holds and can change owner/admin
contract AdminVault {
address public owner;
address public admin;
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
require(admin == msg.sender, "msg.sender not admin");
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
require(admin == msg.sender, "msg.sender not admin");
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD);
modifier onlyOwner() {
require(adminVault.owner() == msg.sender, "msg.sender not owner");
_;
}
modifier onlyAdmin() {
require(adminVault.admin() == msg.sender, "msg.sender not admin");
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists";
string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists";
string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process";
string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger";
string public constant ERR_CHANGE_NOT_READY = "Change not ready yet";
string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0";
string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change";
string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change";
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes32 => Entry) public entries;
mapping(bytes32 => address) public previousAddresses;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes32 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes32 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS);
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Reverts to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR);
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE);
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE);
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
}
/// @title Implements Action interface and common helpers for passing inputs
abstract contract ActionBase is AdminAuth {
address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C;
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value";
string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value";
/// @dev Subscription params index range [128, 255]
uint8 public constant SUB_MIN_INDEX_VALUE = 128;
uint8 public constant SUB_MAX_INDEX_VALUE = 255;
/// @dev Return params index range [1, 127]
uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
uint8 public constant RETURN_MAX_INDEX_VALUE = 127;
/// @dev If the input value should not be replaced
uint8 public constant NO_PARAM_MAPPING = 0;
/// @dev We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
/// @notice Given an addr input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (address) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (address));
}
}
return _param;
}
/// @notice Given an bytes32 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32));
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplaceable(uint8 _type) internal pure returns (bool) {
return _type != NO_PARAM_MAPPING;
}
/// @notice Checks if the paramMapping value is in the return value range
/// @param _type Indicated the type of the input
function isReturnInjection(uint8 _type) internal pure returns (bool) {
return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in return array value
/// @param _type Indicated the type of the input
function getReturnIndex(uint8 _type) internal pure returns (uint8) {
require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE);
return (_type - RETURN_MIN_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in sub array value
/// @param _type Indicated the type of the input
function getSubIndex(uint8 _type) internal pure returns (uint8) {
require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE);
return (_type - SUB_MIN_INDEX_VALUE);
}
}
/// @title Supplies liquidity to uniswap
contract UniWithdraw is ActionBase {
using TokenUtils for address;
IUniswapRouter public constant router =
IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory public constant factory =
IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
struct UniWithdrawData {
address tokenA;
address tokenB;
uint256 liquidity;
address to;
address from;
uint256 amountAMin;
uint256 amountBMin;
uint256 deadline;
}
/// @inheritdoc ActionBase
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
UniWithdrawData memory uniData = parseInputs(_callData);
uniData.tokenA = _parseParamAddr(uniData.tokenA, _paramMapping[0], _subData, _returnValues);
uniData.tokenB = _parseParamAddr(uniData.tokenB, _paramMapping[1], _subData, _returnValues);
uniData.liquidity = _parseParamUint(
uniData.liquidity,
_paramMapping[2],
_subData,
_returnValues
);
uniData.to = _parseParamAddr(uniData.to, _paramMapping[3], _subData, _returnValues);
uniData.from = _parseParamAddr(uniData.from, _paramMapping[4], _subData, _returnValues);
uint256 liqAmount = _uniWithdraw(uniData);
return bytes32(liqAmount);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable override {
UniWithdrawData memory uniData = parseInputs(_callData);
_uniWithdraw(uniData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Removes liquidity from uniswap
/// @param _uniData All the required data to withdraw from uni
function _uniWithdraw(UniWithdrawData memory _uniData) internal returns (uint256) {
address lpTokenAddr = factory.getPair(_uniData.tokenA, _uniData.tokenB);
uint pulledTokens = lpTokenAddr.pullTokensIfNeeded(_uniData.from, _uniData.liquidity);
lpTokenAddr.approveToken(address(router), pulledTokens);
_uniData.liquidity = pulledTokens;
// withdraw liq. and get info how much we got out
(uint256 amountA, uint256 amountB) = _withdrawLiquidity(_uniData);
logger.Log(
address(this),
msg.sender,
"UniWithdraw",
abi.encode(_uniData, amountA, amountB)
);
return _uniData.liquidity;
}
function _withdrawLiquidity(UniWithdrawData memory _uniData)
internal
returns (uint256 amountA, uint256 amountB)
{
(amountA, amountB) = router.removeLiquidity(
_uniData.tokenA,
_uniData.tokenB,
_uniData.liquidity,
_uniData.amountAMin,
_uniData.amountBMin,
_uniData.to,
_uniData.deadline
);
}
function parseInputs(bytes[] memory _callData)
internal
pure
returns (UniWithdrawData memory uniData)
{
uniData = abi.decode(_callData[0], (UniWithdrawData));
}
}
|
@inheritdoc ActionBase
|
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
UniWithdrawData memory uniData = parseInputs(_callData);
uniData.tokenA = _parseParamAddr(uniData.tokenA, _paramMapping[0], _subData, _returnValues);
uniData.tokenB = _parseParamAddr(uniData.tokenB, _paramMapping[1], _subData, _returnValues);
uniData.liquidity = _parseParamUint(
uniData.liquidity,
_paramMapping[2],
_subData,
_returnValues
);
uniData.to = _parseParamAddr(uniData.to, _paramMapping[3], _subData, _returnValues);
uniData.from = _parseParamAddr(uniData.from, _paramMapping[4], _subData, _returnValues);
uint256 liqAmount = _uniWithdraw(uniData);
return bytes32(liqAmount);
}
| 2,110,326
|
./full_match/4/0x18Be7dB1a84062eE9e7361A686495d7b3Fc97a26/sources/contracts/TradingContract.sol
|
Getter for the total supply converted to WETH
|
function getTotalSupply() public view returns (uint256) {
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _convertedBaseBalance = getAmountOutMin(baseTokenAddress, WETHAddress, _baseTokenBalance);
uint256 _convertedPairedBalance = getAmountOutMin(pairedTokenAddress, WETHAddress, _pairedTokenBalance);
return _convertedBaseBalance.add(_convertedPairedBalance);
}
| 658,687
|
//Address: 0x8426d0dc03335d4a391bf4cf7fe546ff89549de4
//Contract name: BlokToken
//Balance: 0 Ether
//Verification Date: 4/8/2018
//Transacion Count: 93
// CODE STARTS HERE
pragma solidity ^0.4.13;
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
revert();
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @dev Gets the balance of the specified address.
/// @param _owner address The address to query the the balance of.
/// @return uint256 representing the amount owned by the passed address.
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev transfer token to a specified address.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/// @dev Transfer tokens from one address to another.
/// @param _from address The address which you want to send tokens from.
/// @param _to address The address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
}
contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev The Ownable constructor sets the original `owner` of the contract to the sender
/// account.
function Ownable() {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
modifier onlyOwnerCandidate() {
if (msg.sender != newOwnerCandidate) {
revert();
}
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the previously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal 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 returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract TokenHolder is Ownable {
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) onlyOwner returns (bool success) {
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
contract BlokToken is Ownable, BasicToken, TokenHolder {
using SafeMath for uint256;
string public constant name = "Blok";
string public constant symbol = "BLO";
// Using same decimal value as ETH (makes ETH-BLO conversion much easier).
uint8 public constant decimals = 18;
// States whether creating more tokens is allowed or not.
// Used during token sale.
bool public isMinting = true;
event MintingEnded();
modifier onlyDuringMinting() {
require(isMinting);
_;
}
modifier onlyAfterMinting() {
require(!isMinting);
_;
}
/// @dev Mint Blok tokens.
/// @param _to address Address to send minted Blok to.
/// @param _amount uint256 Amount of Blok tokens to mint.
function mint(address _to, uint256 _amount) external onlyOwner onlyDuringMinting {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(0x0, _to, _amount);
}
/// @dev End minting mode.
function endMinting() external onlyOwner {
if (isMinting == false) {
return;
}
isMinting = false;
MintingEnded();
}
/// @dev Same ERC20 behavior, but reverts if still minting.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public onlyAfterMinting returns (bool) {
return super.approve(_spender, _value);
}
/// @dev Same ERC20 behavior, but reverts if still minting.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public onlyAfterMinting returns (bool) {
return super.transfer(_to, _value);
}
/// @dev Same ERC20 behavior, but reverts if still minting.
/// @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 onlyAfterMinting returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract BlokTokenSale is Ownable, TokenHolder {
using SafeMath for uint256;
// External parties:
// BLO token contract.
BlokToken public blok;
// Vesting contract for pre-sale participants.
VestingTrustee public trustee;
// Received funds are forwarded to this address.
address public fundingRecipient;
// Blok token unit.
// Using same decimal value as ETH (makes ETH-BLO conversion much easier).
// This is the same as in Blok token contract.
uint256 public constant TOKEN_UNIT = 10 ** 18;
// Maximum number of tokens in circulation: 10 trillion.
uint256 public constant MAX_TOKENS = 360000000 * TOKEN_UNIT;
// Maximum tokens offered in the sale.
uint256 public constant MAX_TOKENS_SOLD = 234000000 * TOKEN_UNIT;
// BLO to 1 wei ratio.
uint256 public constant BLO_PER_WEI = 5700;
// Sale start and end timestamps.
uint256 public constant SALE_DURATION = 30 days;
uint256 public startTime;
uint256 public endTime;
// Amount of tokens sold until now in the sale.
uint256 public tokensSold = 0;
// Participation caps, according to KYC tiers.
uint256 public constant TIER_1_CAP = 20000 ether; // Maximum uint256 value
// Accumulated amount each participant has contributed so far.
mapping (address => uint256) public participationHistory;
// Maximum amount that each participant is allowed to contribute (in WEI).
mapping (address => uint256) public participationCaps;
// Maximum amount ANYBODY is currently allowed to contribute.
uint256 public hardParticipationCap = uint256(-1);
// Vesting information for special addresses:
struct TokenGrant {
uint256 value;
uint256 startOffset;
uint256 cliffOffset;
uint256 endOffset;
uint256 installmentLength;
uint8 percentVested;
}
address[] public tokenGrantees;
mapping (address => TokenGrant) public tokenGrants;
uint256 public lastGrantedIndex = 0;
uint256 public constant MAX_TOKEN_GRANTEES = 100;
uint256 public constant GRANT_BATCH_SIZE = 10;
address public constant RESERVE_TOKENS = 0xA67E1c56A5e0363B61a23670FFC0FcD8F09f178d;
address public constant TEAM_WALLET = 0x52aA6A62404107742ac01Ff247ED47b49b16c40A;
address public constant BOUNTY_WALLET = 0xCf1e64Ce2740A03192F1d7a3234AABd88c025c4B;
event TokensIssued(address indexed _to, uint256 _tokens);
/// @dev Reverts if called when not during sale.
modifier onlyDuringSale() {
require(!saleEnded() && now >= startTime);
_;
}
/// @dev Reverts if called before sale ends.
modifier onlyAfterSale() {
require(saleEnded());
_;
}
/// @dev Constructor that initializes the sale conditions.
/// @param _fundingRecipient address The address of the funding recipient.
/// @param _startTime uint256 The start time of the token sale.
function BlokTokenSale(address _fundingRecipient, uint256 _startTime) {
require(_fundingRecipient != address(0));
require(_startTime > now);
// Deploy new BlokToken contract.
blok = new BlokToken();
// Deploy new VestingTrustee contract.
trustee = new VestingTrustee(blok);
fundingRecipient = _fundingRecipient;
startTime = _startTime;
endTime = startTime + SALE_DURATION;
// Initialize special vesting grants.
initTokenGrants();
}
/// @dev Initialize token grants.
function initTokenGrants() private onlyOwner {
tokenGrantees.push(RESERVE_TOKENS);
tokenGrants[RESERVE_TOKENS] = TokenGrant(MAX_TOKENS.mul(18).div(100), 0, 0, 10 days, 1 days, 0);
tokenGrantees.push(TEAM_WALLET);
tokenGrants[TEAM_WALLET] = TokenGrant(MAX_TOKENS.mul(13).div(100), 0, 0, 10 days, 1 days, 0);
tokenGrantees.push(BOUNTY_WALLET);
tokenGrants[BOUNTY_WALLET] = TokenGrant(MAX_TOKENS.mul(4).div(100), 0, 0, 10 days, 1 days, 0);
}
/// @dev Adds a Blok token vesting grant.
/// @param _grantee address The address of the token grantee. Can be granted only once.
/// @param _value uint256 The value of the grant.
function addTokenGrant(address _grantee, uint256 _value) external onlyOwner {
require(_grantee != address(0));
require(_value > 0);
require(tokenGrantees.length + 1 <= MAX_TOKEN_GRANTEES);
// Verify the grant doesn't already exist.
require(tokenGrants[_grantee].value == 0);
for (uint i = 0; i < tokenGrantees.length; i++) {
require(tokenGrantees[i] != _grantee);
}
// Add grant and add to grantee list.
tokenGrantees.push(_grantee);
tokenGrants[_grantee] = TokenGrant(_value, 0, 1 years, 1 years, 1 days, 50);
}
/// @dev Deletes a Blok token grant.
/// @param _grantee address The address of the token grantee.
function deleteTokenGrant(address _grantee) external onlyOwner {
require(_grantee != address(0));
// Delete the grant from the keys array.
for (uint i = 0; i < tokenGrantees.length; i++) {
if (tokenGrantees[i] == _grantee) {
delete tokenGrantees[i];
break;
}
}
// Delete the grant from the mapping.
delete tokenGrants[_grantee];
}
/// @dev Add a list of participants to a capped participation tier.
/// @param _participants address[] The list of participant addresses.
/// @param _cap uint256 The cap amount (in ETH).
function setParticipationCap(address[] _participants, uint256 _cap) private onlyOwner {
for (uint i = 0; i < _participants.length; i++) {
participationCaps[_participants[i]] = _cap;
}
}
/// @dev Add a list of participants to cap tier #1.
/// @param _participants address[] The list of participant addresses.
function setTier1Participants(address[] _participants) external onlyOwner {
setParticipationCap(_participants, TIER_1_CAP);
}
/// @dev Set hard participation cap for all participants.
/// @param _cap uint256 The hard cap amount.
function setHardParticipationCap(uint256 _cap) external onlyOwner {
require(_cap > 0);
hardParticipationCap = _cap;
}
/// @dev Fallback function that will delegate the request to create().
function () external payable onlyDuringSale {
create(msg.sender);
}
/// @dev Create and sell tokens to the caller.
/// @param _recipient address The address of the recipient receiving the tokens.
function create(address _recipient) public payable onlyDuringSale {
require(_recipient != address(0));
// Enforce participation cap (in Wei received).
uint256 weiAlreadyParticipated = participationHistory[msg.sender];
uint256 participationCap = SafeMath.min256(TOKEN_UNIT.mul(15).add(participationCaps[msg.sender]), hardParticipationCap);
uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated));
require(cappedWeiReceived > 0);
// Accept funds and transfer to funding recipient.
uint256 weiLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold).div(BLO_PER_WEI);
uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale);
participationHistory[msg.sender] = weiAlreadyParticipated.add(weiToParticipate);
fundingRecipient.transfer(weiToParticipate);
// Issue tokens and transfer to recipient.
uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
uint256 tokensToIssue = weiToParticipate.mul(BLO_PER_WEI);
if (tokensLeftInSale.sub(tokensToIssue) < BLO_PER_WEI) {
// If purchase would cause less than BLO_PER_WEI tokens left then nobody could ever buy them.
// So, gift them to the last buyer.
tokensToIssue = tokensLeftInSale;
}
tokensSold = tokensSold.add(tokensToIssue);
issueTokens(_recipient, tokensToIssue);
// Partial refund if full participation not possible
// e.g. due to cap being reached.
uint256 refund = msg.value.sub(weiToParticipate);
if (refund > 0) {
msg.sender.transfer(refund);
}
}
/// @dev Finalizes the token sale event, by stopping token minting.
function finalize() external onlyAfterSale onlyOwner {
if (!blok.isMinting()) {
revert();
}
require(lastGrantedIndex == tokenGrantees.length);
// Finish minting.
blok.endMinting();
}
/// @dev Grants pre-configured token grants in batches. When the method is called, it'll resume from the last grant,
/// from its previous run, and will finish either after granting GRANT_BATCH_SIZE grants or finishing the whole list
/// of grants.
function grantTokens() external onlyAfterSale onlyOwner {
uint endIndex = SafeMath.min256(tokenGrantees.length, lastGrantedIndex + GRANT_BATCH_SIZE);
for (uint i = lastGrantedIndex; i < endIndex; i++) {
address grantee = tokenGrantees[i];
// Calculate how many tokens have been granted, vested, and issued such that: granted = vested + issued.
TokenGrant memory tokenGrant = tokenGrants[grantee];
uint256 tokensGranted = tokenGrant.value;
uint256 tokensVesting = tokensGranted.mul(tokenGrant.percentVested).div(100);
uint256 tokensIssued = tokensGranted.sub(tokensVesting);
// Transfer issued tokens that have yet to be transferred to grantee.
if (tokensIssued > 0) {
issueTokens(grantee, tokensIssued);
}
// Transfer vested tokens that have yet to be transferred to vesting trustee, and initialize grant.
if (tokensVesting > 0) {
issueTokens(trustee, tokensVesting);
trustee.grant(grantee, tokensVesting, now.add(tokenGrant.startOffset), now.add(tokenGrant.cliffOffset),
now.add(tokenGrant.endOffset), tokenGrant.installmentLength, true);
}
lastGrantedIndex++;
}
}
/// @dev Issues tokens for the recipient.
/// @param _recipient address The address of the recipient.
/// @param _tokens uint256 The amount of tokens to issue.
function issueTokens(address _recipient, uint256 _tokens) private {
// Request Blok token contract to mint the requested tokens for the buyer.
blok.mint(_recipient, _tokens);
TokensIssued(_recipient, _tokens);
}
/// @dev Returns whether the sale has ended.
/// @return bool Whether the sale has ended or not.
function saleEnded() private constant returns (bool) {
return tokensSold >= MAX_TOKENS_SOLD || now >= endTime;
}
/// @dev Requests to transfer control of the Blok token contract to a new owner.
/// @param _newOwnerCandidate address The address to transfer ownership to.
///
/// NOTE:
/// 1. The new owner will need to call Blok token contract's acceptOwnership directly in order to accept the ownership.
/// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of
/// the Blok token contract can issue new tokens.
function requestBlokTokenOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
blok.requestOwnershipTransfer(_newOwnerCandidate);
}
/// @dev Accepts new ownership on behalf of the Blok token contract.
// This can be used by the sale contract itself to claim back ownership of the Blok token contract.
function acceptBlokTokenOwnership() external onlyOwner {
blok.acceptOwnership();
}
/// @dev Requests to transfer control of the VestingTrustee contract to a new owner.
/// @param _newOwnerCandidate address The address to transfer ownership to.
///
/// NOTE:
/// 1. The new owner will need to call VestingTrustee's acceptOwnership directly in order to accept the ownership.
/// 2. Calling this method during the token sale will prevent the token sale from finalizaing, since only the owner
/// of the VestingTrustee contract can issue new token grants.
function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
trustee.requestOwnershipTransfer(_newOwnerCandidate);
}
/// @dev Accepts new ownership on behalf of the VestingTrustee contract.
/// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract.
function acceptVestingTrusteeOwnership() external onlyOwner {
trustee.acceptOwnership();
}
}
contract VestingTrustee is Ownable {
using SafeMath for uint256;
// Blok token contract.
BlokToken public blok;
// Vesting grant for a speicifc holder.
struct Grant {
uint256 value;
uint256 start;
uint256 cliff;
uint256 end;
uint256 installmentLength; // In seconds.
uint256 transferred;
bool revokable;
}
// Holder to grant information mapping.
mapping (address => Grant) public grants;
// Total tokens available for vesting.
uint256 public totalVesting;
event NewGrant(address indexed _from, address indexed _to, uint256 _value);
event TokensUnlocked(address indexed _to, uint256 _value);
event GrantRevoked(address indexed _holder, uint256 _refund);
/// @dev Constructor that initializes the address of the Blok token contract.
/// @param _blok BlokToken The address of the previously deployed Blok token contract.
function VestingTrustee(BlokToken _blok) {
require(_blok != address(0));
blok = _blok;
}
/// @dev Grant tokens to a specified address.
/// @param _to address The holder address.
/// @param _value uint256 The amount of tokens to be granted.
/// @param _start uint256 The beginning of the vesting period.
/// @param _cliff uint256 Duration of the cliff period (when the first installment is made).
/// @param _end uint256 The end of the vesting period.
/// @param _installmentLength uint256 The length of each vesting installment (in seconds).
/// @param _revokable bool Whether the grant is revokable or not.
function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable)
external onlyOwner {
require(_to != address(0));
require(_to != address(this)); // Don't allow holder to be this contract.
require(_value > 0);
// Require that every holder can be granted tokens only once.
require(grants[_to].value == 0);
// Require for time ranges to be consistent and valid.
require(_start <= _cliff && _cliff <= _end);
// Require installment length to be valid and no longer than (end - start).
require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));
// Grant must not exceed the total amount of tokens currently available for vesting.
require(totalVesting.add(_value) <= blok.balanceOf(address(this)));
// Assign a new grant.
grants[_to] = Grant({
value: _value,
start: _start,
cliff: _cliff,
end: _end,
installmentLength: _installmentLength,
transferred: 0,
revokable: _revokable
});
// Since tokens have been granted, reduce the total amount available for vesting.
totalVesting = totalVesting.add(_value);
NewGrant(msg.sender, _to, _value);
}
/// @dev Revoke the grant of tokens of a specifed address.
/// @param _holder The address which will have its tokens revoked.
function revoke(address _holder) public onlyOwner {
Grant memory grant = grants[_holder];
// Grant must be revokable.
require(grant.revokable);
// Calculate amount of remaining tokens that are still available to be
// returned to owner.
uint256 refund = grant.value.sub(grant.transferred);
// Remove grant information.
delete grants[_holder];
// Update total vesting amount and transfer previously calculated tokens to owner.
totalVesting = totalVesting.sub(refund);
blok.transfer(msg.sender, refund);
GrantRevoked(_holder, refund);
}
/// @dev Calculate the total amount of vested tokens of a holder at a given time.
/// @param _holder address The address of the holder.
/// @param _time uint256 The specific time to calculate against.
/// @return a uint256 Representing a holder's total amount of vested tokens.
function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) {
Grant memory grant = grants[_holder];
if (grant.value == 0) {
return 0;
}
return calculateVestedTokens(grant, _time);
}
/// @dev Calculate amount of vested tokens at a specifc time.
/// @param _grant Grant The vesting grant.
/// @param _time uint256 The time to be checked
/// @return a uint256 Representing the amount of vested tokens of a specific grant.
function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) {
// If we're before the cliff, then nothing is vested.
if (_time < _grant.cliff) {
return 0;
}
// If we're after the end of the vesting period - everything is vested;
if (_time >= _grant.end) {
return _grant.value;
}
// Calculate amount of installments past until now.
//
// NOTE result gets floored because of integer division.
uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength);
// Calculate amount of days in entire vesting period.
uint256 vestingDays = _grant.end.sub(_grant.start);
// Calculate and return installments that have passed according to vesting days that have passed.
return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays);
}
/// @dev Unlock vested tokens and transfer them to their holder.
/// @return a uint256 Representing the amount of vested tokens transferred to their holder.
function unlockVestedTokens() external {
Grant storage grant = grants[msg.sender];
// Require that there will be funds left in grant to tranfser to holder.
require(grant.value != 0);
// Get the total amount of vested tokens, acccording to grant.
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
return;
}
// Make sure the holder doesn't transfer more than what he already has.
uint256 transferable = vested.sub(grant.transferred);
if (transferable == 0) {
return;
}
// Update transferred and total vesting amount, then transfer remaining vested funds to holder.
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
blok.transfer(msg.sender, transferable);
TokensUnlocked(msg.sender, transferable);
}
}
|
Calculate amount of vested tokens at a specifc time. _grant Grant The vesting grant. _time uint256 The time to be checked return a uint256 Representing the amount of vested tokens of a specific grant. If we're before the cliff, then nothing is vested. If we're after the end of the vesting period - everything is vested;
|
function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) {
if (_time < _grant.cliff) {
return 0;
}
if (_time >= _grant.end) {
return _grant.value;
}
}
| 2,519,941
|
./partial_match/3/0xcf9582e420Bcf9c6c6885C0181e008F30B0d060B/sources/MMM8_Exchange.sol
|
deduct commissions for referrals fire event
|
function purchaseTokens(uint256 _incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _taxedEthereum = _incomingEthereum;
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum );
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
emit Transfer(address(this), _customerAddress, _amountOfTokens);
return _amountOfTokens;
}
| 5,249,598
|
// Copyright (C) 2020 Zerion Inc. <https://zerion.io>
//
// 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 <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.7.3;
pragma experimental ABIEncoderV2;
import { AdapterBalance, TokenBalance } from "../shared/Structs.sol";
import { ERC20 } from "../shared/ERC20.sol";
import { Ownable } from "./Ownable.sol";
import { ProtocolAdapterManager } from "./ProtocolAdapterManager.sol";
import { ProtocolAdapter } from "../adapters/ProtocolAdapter.sol";
/**
* @title Registry for protocol adapters.
* @notice getBalances() function implements the main functionality.
* @author Igor Sobolev <sobolev@zerion.io>
*/
contract ProtocolAdapterRegistry is Ownable, ProtocolAdapterManager {
/**
* @param account Address of the account.
* @return AdapterBalance array by the given account.
* @notice Zero values are filtered out!
*/
function getBalances(address account) external returns (AdapterBalance[] memory) {
AdapterBalance[] memory adapterBalances =
getAdapterBalances(getProtocolAdapterNames(), account);
(uint256 nonZeroAdapterBalancesNumber, uint256[] memory nonZeroTokenBalancesNumbers) =
getNonZeroAdapterBalancesAndTokenBalancesNumbers(adapterBalances);
return
getNonZeroAdapterBalances(
adapterBalances,
nonZeroAdapterBalancesNumber,
nonZeroTokenBalancesNumbers
);
}
/**
* @param protocolAdapterNames Array of the protocol adapters' names.
* @param account Address of the account.
* @return AdapterBalance array by the given parameters.
*/
function getAdapterBalances(bytes32[] memory protocolAdapterNames, address account)
public
returns (AdapterBalance[] memory)
{
uint256 length = protocolAdapterNames.length;
AdapterBalance[] memory adapterBalances = new AdapterBalance[](length);
for (uint256 i = 0; i < length; i++) {
adapterBalances[i] = getAdapterBalance(
protocolAdapterNames[i],
getSupportedTokens(protocolAdapterNames[i]),
account
);
}
return adapterBalances;
}
/**
* @param protocolAdapterName Protocol adapter's Name.
* @param tokens Array of tokens' addresses.
* @param account Address of the account.
* @return AdapterBalance array by the given parameters.
*/
function getAdapterBalance(
bytes32 protocolAdapterName,
address[] memory tokens,
address account
) public returns (AdapterBalance memory) {
address adapter = getProtocolAdapterAddress(protocolAdapterName);
require(adapter != address(0), "AR: bad protocolAdapterName");
uint256 length = tokens.length;
TokenBalance[] memory tokenBalances = new TokenBalance[](tokens.length);
for (uint256 i = 0; i < length; i++) {
try ProtocolAdapter(adapter).getBalance(tokens[i], account) returns (int256 amount) {
tokenBalances[i] = TokenBalance({ token: tokens[i], amount: amount });
} catch {
tokenBalances[i] = TokenBalance({ token: tokens[i], amount: 0 });
}
}
return
AdapterBalance({
protocolAdapterName: protocolAdapterName,
tokenBalances: tokenBalances
});
}
/**
* @param adapterBalances List of AdapterBalance structs.
* @return Numbers of non-empty AdapterBalance and non-zero TokenBalance structs.
*/
function getNonZeroAdapterBalancesAndTokenBalancesNumbers(
AdapterBalance[] memory adapterBalances
) internal returns (uint256, uint256[] memory) {
uint256 length = adapterBalances.length;
uint256 nonZeroAdapterBalancesNumber = 0;
uint256[] memory nonZeroTokenBalancesNumbers = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
nonZeroTokenBalancesNumbers[i] = getNonZeroTokenBalancesNumber(
adapterBalances[i].tokenBalances
);
if (nonZeroTokenBalancesNumbers[i] > 0) {
nonZeroAdapterBalancesNumber++;
}
}
return (nonZeroAdapterBalancesNumber, nonZeroTokenBalancesNumbers);
}
/**
* @param tokenBalances List of TokenBalance structs.
* @return Number of non-zero TokenBalance structs.
*/
function getNonZeroTokenBalancesNumber(TokenBalance[] memory tokenBalances)
internal
returns (uint256)
{
uint256 length = tokenBalances.length;
uint256 nonZeroTokenBalancesNumber = 0;
for (uint256 i = 0; i < length; i++) {
if (tokenBalances[i].amount > 0) {
nonZeroTokenBalancesNumber++;
}
}
return nonZeroTokenBalancesNumber;
}
/**
* @param adapterBalances List of AdapterBalance structs.
* @param nonZeroAdapterBalancesNumber Number of non-empty AdapterBalance structs.
* @param nonZeroTokenBalancesNumbers List of non-zero TokenBalance structs numbers.
* @return Non-empty AdapterBalance structs with non-zero TokenBalance structs.
*/
function getNonZeroAdapterBalances(
AdapterBalance[] memory adapterBalances,
uint256 nonZeroAdapterBalancesNumber,
uint256[] memory nonZeroTokenBalancesNumbers
) internal returns (AdapterBalance[] memory) {
AdapterBalance[] memory nonZeroAdapterBalances =
new AdapterBalance[](nonZeroAdapterBalancesNumber);
uint256 length = adapterBalances.length;
uint256 counter = 0;
for (uint256 i = 0; i < length; i++) {
if (nonZeroTokenBalancesNumbers[i] == 0) {
continue;
}
nonZeroAdapterBalances[counter] = AdapterBalance({
protocolAdapterName: adapterBalances[i].protocolAdapterName,
tokenBalances: getNonZeroTokenBalances(
adapterBalances[i].tokenBalances,
nonZeroTokenBalancesNumbers[i]
)
});
counter++;
}
return nonZeroAdapterBalances;
}
/**
* @param tokenBalances List of TokenBalance structs.
* @param nonZeroTokenBalancesNumber Number of non-zero TokenBalance structs.
* @return Non-zero TokenBalance structs.
*/
function getNonZeroTokenBalances(
TokenBalance[] memory tokenBalances,
uint256 nonZeroTokenBalancesNumber
) internal returns (TokenBalance[] memory) {
TokenBalance[] memory nonZeroTokenBalances =
new TokenBalance[](nonZeroTokenBalancesNumber);
uint256 length = tokenBalances.length;
uint256 counter = 0;
for (uint256 i = 0; i < length; i++) {
if (tokenBalances[i].amount == 0) {
continue;
}
nonZeroTokenBalances[counter] = tokenBalances[i];
counter++;
}
return nonZeroTokenBalances;
}
}
|
tokenBalances List of TokenBalance structs. return Number of non-zero TokenBalance structs./
|
function getNonZeroTokenBalancesNumber(TokenBalance[] memory tokenBalances)
internal
returns (uint256)
{
uint256 length = tokenBalances.length;
uint256 nonZeroTokenBalancesNumber = 0;
for (uint256 i = 0; i < length; i++) {
if (tokenBalances[i].amount > 0) {
nonZeroTokenBalancesNumber++;
}
}
return nonZeroTokenBalancesNumber;
}
| 13,120,114
|
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SM1Admin } from '../v1_1/impl/SM1Admin.sol';
import { SM1Getters } from '../v1_1/impl/SM1Getters.sol';
import { SM1Operators } from '../v1_1/impl/SM1Operators.sol';
import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol';
import { SM1Staking } from '../v1_1/impl/SM1Staking.sol';
/**
* @title SafetyModuleV2
* @author dYdX
*
* @notice Contract for staking tokens, which may be slashed by the permissioned slasher.
*
* NOTE: Most functions will revert if epoch zero has not started.
*/
contract SafetyModuleV2 is
SM1Slashing,
SM1Operators,
SM1Admin,
SM1Getters
{
using SafeERC20 for IERC20;
// ============ Constants ============
string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module';
string public constant EIP712_DOMAIN_VERSION = '1';
bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
);
// ============ Constructor ============
constructor(
IERC20 stakedToken,
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{}
// ============ External Functions ============
/**
* @notice Initializer for v2, intended to fix the deployment bug that affected v1.
*
* Responsible for the following:
*
* 1. Funds recovery and staker compensation:
* - Transfer all Safety Module DYDX to the recovery contract.
* - Transfer compensation amount from the rewards treasury to the recovery contract.
*
* 2. Storage recovery and cleanup:
* - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE.
* - Clean up invalid storage values at slots 115 and 125.
*
* @param recoveryContract The address of the contract which will distribute
* recovered funds to stakers.
* @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker
* compensation, on top of the return of staked funds.
*/
function initialize(
address recoveryContract,
uint256 recoveryCompensationAmount
)
external
initializer
{
// Funds recovery and staker compensation.
uint256 balance = STAKED_TOKEN.balanceOf(address(this));
STAKED_TOKEN.safeTransfer(recoveryContract, balance);
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount);
// Storage recovery and cleanup.
__SM1ExchangeRate_init();
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(115, 0)
sstore(125, 0)
}
}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1Admin
* @author dYdX
*
* @dev Admin-only functions.
*/
abstract contract SM1Admin is
SM1StakedBalances,
SM1Roles
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Set the parameters defining the function from timestamp to epoch number.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*
* Reverts if epoch zero already started, and the new parameters would change the current epoch.
* Reverts if epoch zero has not started, but would have had started under the new parameters.
*
* @param interval The length `a` of an epoch, in seconds.
* @param offset The offset `b`, i.e. the start of epoch zero, in seconds.
*/
function setEpochParameters(
uint256 interval,
uint256 offset
)
external
onlyRole(EPOCH_PARAMETERS_ROLE)
nonReentrant
{
if (!hasEpochZeroStarted()) {
require(
block.timestamp < offset,
'SM1Admin: Started epoch zero'
);
_setEpochParameters(interval, offset);
return;
}
// We must settle the total active balance to ensure the index is recorded at the epoch
// boundary as needed, before we make any changes to the epoch formula.
_settleTotalActiveBalance();
// Update the epoch parameters. Require that the current epoch number is unchanged.
uint256 originalCurrentEpoch = getCurrentEpoch();
_setEpochParameters(interval, offset);
uint256 newCurrentEpoch = getCurrentEpoch();
require(
originalCurrentEpoch == newCurrentEpoch,
'SM1Admin: Changed epochs'
);
}
/**
* @notice Set the blackout window, during which one cannot request withdrawals of staked funds.
*/
function setBlackoutWindow(
uint256 blackoutWindow
)
external
onlyRole(EPOCH_PARAMETERS_ROLE)
nonReentrant
{
_setBlackoutWindow(blackoutWindow);
}
/**
* @notice Set the emission rate of rewards.
*
* @param emissionPerSecond The new number of rewards tokens given out per second.
*/
function setRewardsPerSecond(
uint256 emissionPerSecond
)
external
onlyRole(REWARDS_RATE_ROLE)
nonReentrant
{
uint256 totalStaked = 0;
if (hasEpochZeroStarted()) {
// We must settle the total active balance to ensure the index is recorded at the epoch
// boundary as needed, before we make any changes to the emission rate.
totalStaked = _settleTotalActiveBalance();
}
_setRewardsPerSecond(emissionPerSecond, totalStaked);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Getters
* @author dYdX
*
* @dev Some external getter functions.
*/
abstract contract SM1Getters is
SM1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice The parameters specifying the function from timestamp to epoch number.
*
* @return The parameters struct with `interval` and `offset` fields.
*/
function getEpochParameters()
external
view
returns (SM1Types.EpochParameters memory)
{
return _EPOCH_PARAMETERS_;
}
/**
* @notice The period of time at the end of each epoch in which withdrawals cannot be requested.
*
* @return The blackout window duration, in seconds.
*/
function getBlackoutWindow()
external
view
returns (uint256)
{
return _BLACKOUT_WINDOW_;
}
/**
* @notice Get the domain separator used for EIP-712 signatures.
*
* @return The EIP-712 domain separator.
*/
function getDomainSeparator()
external
view
returns (bytes32)
{
return _DOMAIN_SEPARATOR_;
}
/**
* @notice The value of one underlying token, in the units used for staked balances, denominated
* as a mutiple of EXCHANGE_RATE_BASE for additional precision.
*
* To convert from an underlying amount to a staked amount, multiply by the exchange rate.
*
* @return The exchange rate.
*/
function getExchangeRate()
external
view
returns (uint256)
{
return _EXCHANGE_RATE_;
}
/**
* @notice Get an exchange rate snapshot.
*
* @param index The index number of the exchange rate snapshot.
*
* @return The snapshot struct with `blockNumber` and `value` fields.
*/
function getExchangeRateSnapshot(
uint256 index
)
external
view
returns (SM1Types.Snapshot memory)
{
return _EXCHANGE_RATE_SNAPSHOTS_[index];
}
/**
* @notice Get the number of exchange rate snapshots.
*
* @return The number of snapshots that have been taken of the exchange rate.
*/
function getExchangeRateSnapshotCount()
external
view
returns (uint256)
{
return _EXCHANGE_RATE_SNAPSHOT_COUNT_;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1Staking } from './SM1Staking.sol';
/**
* @title SM1Operators
* @author dYdX
*
* @dev Actions which may be called by authorized operators, nominated by the contract owner.
*
* There are two types of operators. These should be smart contracts, which can be used to
* provide additional functionality to users:
*
* STAKE_OPERATOR_ROLE:
*
* This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This
* role could be used by a smart contract to provide a staking interface with additional
* features, for example, optional lock-up periods that pay out additional rewards (from a
* separate rewards pool).
*
* CLAIM_OPERATOR_ROLE:
*
* This operator is allowed to claim rewards on behalf of stakers. This role could be used by a
* smart contract to provide an interface for claiming rewards from multiple incentive programs
* at once.
*/
abstract contract SM1Operators is
SM1Staking,
SM1Roles
{
using SafeMath for uint256;
// ============ Events ============
event OperatorStakedFor(
address indexed staker,
uint256 amount,
address operator
);
event OperatorWithdrawalRequestedFor(
address indexed staker,
uint256 amount,
address operator
);
event OperatorWithdrewStakeFor(
address indexed staker,
address recipient,
uint256 amount,
address operator
);
event OperatorClaimedRewardsFor(
address indexed staker,
address recipient,
uint256 claimedRewards,
address operator
);
// ============ External Functions ============
/**
* @notice Request a withdrawal on behalf of a staker.
*
* Reverts if we are currently in the blackout window.
*
* @param staker The staker whose stake to request a withdrawal for.
* @param stakeAmount The amount of stake to move from the active to the inactive balance.
*/
function requestWithdrawalFor(
address staker,
uint256 stakeAmount
)
external
onlyRole(STAKE_OPERATOR_ROLE)
nonReentrant
{
_requestWithdrawal(staker, stakeAmount);
emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender);
}
/**
* @notice Withdraw a staker's stake, and send to the specified recipient.
*
* @param staker The staker whose stake to withdraw.
* @param recipient The address that should receive the funds.
* @param stakeAmount The amount of stake to withdraw from the staker's inactive balance.
*/
function withdrawStakeFor(
address staker,
address recipient,
uint256 stakeAmount
)
external
onlyRole(STAKE_OPERATOR_ROLE)
nonReentrant
{
_withdrawStake(staker, recipient, stakeAmount);
emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender);
}
/**
* @notice Claim rewards on behalf of a staker, and send them to the specified recipient.
*
* @param staker The staker whose rewards to claim.
* @param recipient The address that should receive the funds.
*
* @return The number of rewards tokens claimed.
*/
function claimRewardsFor(
address staker,
address recipient
)
external
onlyRole(CLAIM_OPERATOR_ROLE)
nonReentrant
returns (uint256)
{
uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally.
emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender);
return rewards;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1Staking } from './SM1Staking.sol';
/**
* @title SM1Slashing
* @author dYdX
*
* @dev Provides the slashing function for removing funds from the contract.
*
* SLASHING:
*
* All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating
* the exchange rate, and to simplify the technical implementation, we disallow full slashes.
* To reduce the possibility of overflow in the exchange rate, we place an upper bound on the
* fraction of funds that may be slashed in a single slash.
*
* Warning: Slashing is not possible if the slash would cause the exchange rate to overflow.
*
* REWARDS AND GOVERNANCE POWER ACCOUNTING:
*
* Since all slashes are accounted for by a global exchange rate, slashes do not require any
* update to staked balances. The earning of rewards is unaffected by slashes.
*
* Governance power takes slashes into account by using snapshots of the exchange rate inside
* the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of
* the end of the specified block.
*/
abstract contract SM1Slashing is
SM1Staking,
SM1Roles
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice The maximum fraction of funds that may be slashed in a single slash (numerator).
uint256 public constant MAX_SLASH_NUMERATOR = 95;
/// @notice The maximum fraction of funds that may be slashed in a single slash (denominator).
uint256 public constant MAX_SLASH_DENOMINATOR = 100;
// ============ Events ============
event Slashed(
uint256 amount,
address recipient,
uint256 newExchangeRate
);
// ============ External Functions ============
/**
* @notice Slash staked token balances and withdraw those funds to the specified address.
*
* @param requestedSlashAmount The request slash amount, denominated in the underlying token.
* @param recipient The address to receive the slashed tokens.
*
* @return The amount slashed, denominated in the underlying token.
*/
function slash(
uint256 requestedSlashAmount,
address recipient
)
external
onlyRole(SLASHER_ROLE)
nonReentrant
returns (uint256)
{
uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this));
if (underlyingBalance == 0) {
return 0;
}
// Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero.
uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR);
uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount);
uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount);
if (slashAmount == 0) {
return 0;
}
// Update the exchange rate.
//
// Warning: Can revert if the max exchange rate is exceeded.
uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash);
// Transfer the slashed token.
STAKED_TOKEN.safeTransfer(recipient, slashAmount);
emit Slashed(slashAmount, recipient, newExchangeRate);
return slashAmount;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1ERC20 } from './SM1ERC20.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1Staking
* @author dYdX
*
* @dev External functions for stakers. See SM1StakedBalances for details on staker accounting.
*
* UNDERLYING AND STAKED AMOUNTS:
*
* We distinguish between underlying amounts and stake amounts. An underlying amount is denoted
* in the original units of the token being staked. A stake amount is adjusted by the exchange
* rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate
* is equal to one.
*/
abstract contract SM1Staking is
SM1StakedBalances,
SM1ERC20
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Events ============
event Staked(
address indexed staker,
address spender,
uint256 underlyingAmount,
uint256 stakeAmount
);
event WithdrawalRequested(
address indexed staker,
uint256 stakeAmount
);
event WithdrewStake(
address indexed staker,
address recipient,
uint256 underlyingAmount,
uint256 stakeAmount
);
// ============ Constants ============
IERC20 public immutable STAKED_TOKEN;
// ============ Constructor ============
constructor(
IERC20 stakedToken,
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{
STAKED_TOKEN = stakedToken;
}
// ============ External Functions ============
/**
* @notice Deposit and stake funds. These funds are active and start earning rewards immediately.
*
* @param underlyingAmount The amount of underlying token to stake.
*/
function stake(
uint256 underlyingAmount
)
external
nonReentrant
{
_stake(msg.sender, underlyingAmount);
}
/**
* @notice Deposit and stake on behalf of another address.
*
* @param staker The staker who will receive the stake.
* @param underlyingAmount The amount of underlying token to stake.
*/
function stakeFor(
address staker,
uint256 underlyingAmount
)
external
nonReentrant
{
_stake(staker, underlyingAmount);
}
/**
* @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive”
* and available for withdrawal. Inactive funds do not earn rewards.
*
* Reverts if we are currently in the blackout window.
*
* @param stakeAmount The amount of stake to move from the active to the inactive balance.
*/
function requestWithdrawal(
uint256 stakeAmount
)
external
nonReentrant
{
_requestWithdrawal(msg.sender, stakeAmount);
}
/**
* @notice Withdraw the sender's inactive funds, and send to the specified recipient.
*
* @param recipient The address that should receive the funds.
* @param stakeAmount The amount of stake to withdraw from the sender's inactive balance.
*/
function withdrawStake(
address recipient,
uint256 stakeAmount
)
external
nonReentrant
{
_withdrawStake(msg.sender, recipient, stakeAmount);
}
/**
* @notice Withdraw the max available inactive funds, and send to the specified recipient.
*
* This is less gas-efficient than querying the max via eth_call and calling withdrawStake().
*
* @param recipient The address that should receive the funds.
*
* @return The withdrawn amount.
*/
function withdrawMaxStake(
address recipient
)
external
nonReentrant
returns (uint256)
{
uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender);
_withdrawStake(msg.sender, recipient, stakeAmount);
return stakeAmount;
}
/**
* @notice Settle and claim all rewards, and send them to the specified recipient.
*
* Call this function with eth_call to query the claimable rewards balance.
*
* @param recipient The address that should receive the funds.
*
* @return The number of rewards tokens claimed.
*/
function claimRewards(
address recipient
)
external
nonReentrant
returns (uint256)
{
return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally.
}
// ============ Public Functions ============
/**
* @notice Get the amount of stake available for a given staker to withdraw.
*
* @param staker The address whose balance to check.
*
* @return The staker's stake amount that is inactive and available to withdraw.
*/
function getStakeAvailableToWithdraw(
address staker
)
public
view
returns (uint256)
{
// Note that the next epoch inactive balance is always at least that of the current epoch.
return getInactiveBalanceCurrentEpoch(staker);
}
// ============ Internal Functions ============
function _stake(
address staker,
uint256 underlyingAmount
)
internal
{
// Convert using the exchange rate.
uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount);
// Update staked balances and delegate snapshots.
_increaseCurrentAndNextActiveBalance(staker, stakeAmount);
_moveDelegatesForTransfer(address(0), staker, stakeAmount);
// Transfer token from the sender.
STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount);
emit Staked(staker, msg.sender, underlyingAmount, stakeAmount);
emit Transfer(address(0), msg.sender, stakeAmount);
}
function _requestWithdrawal(
address staker,
uint256 stakeAmount
)
internal
{
require(
!inBlackoutWindow(),
'SM1Staking: Withdraw requests restricted in the blackout window'
);
// Get the staker's requestable amount and revert if there is not enough to request withdrawal.
uint256 requestableBalance = getActiveBalanceNextEpoch(staker);
require(
stakeAmount <= requestableBalance,
'SM1Staking: Withdraw request exceeds next active balance'
);
// Move amount from active to inactive in the next epoch.
_moveNextBalanceActiveToInactive(staker, stakeAmount);
emit WithdrawalRequested(staker, stakeAmount);
}
function _withdrawStake(
address staker,
address recipient,
uint256 stakeAmount
)
internal
{
// Get staker withdrawable balance and revert if there is not enough to withdraw.
uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker);
require(
stakeAmount <= withdrawableBalance,
'SM1Staking: Withdraw amount exceeds staker inactive balance'
);
// Update staked balances and delegate snapshots.
_decreaseCurrentAndNextInactiveBalance(staker, stakeAmount);
_moveDelegatesForTransfer(staker, address(0), stakeAmount);
// Convert using the exchange rate.
uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount);
// Transfer token to the recipient.
STAKED_TOKEN.safeTransfer(recipient, underlyingAmount);
emit Transfer(msg.sender, address(0), stakeAmount);
emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.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 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');
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
library SM1Types {
/**
* @dev The parameters used to convert a timestamp to an epoch number.
*/
struct EpochParameters {
uint128 interval;
uint128 offset;
}
/**
* @dev Snapshot of a value at a specific block, used to track historical governance power.
*/
struct Snapshot {
uint256 blockNumber;
uint256 value;
}
/**
* @dev A balance, possibly with a change scheduled for the next epoch.
*
* @param currentEpoch The epoch in which the balance was last updated.
* @param currentEpochBalance The balance at epoch `currentEpoch`.
* @param nextEpochBalance The balance at epoch `currentEpoch + 1`.
*/
struct StoredBalance {
uint16 currentEpoch;
uint240 currentEpochBalance;
uint240 nextEpochBalance;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Roles
* @author dYdX
*
* @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers
* of each role are described below.
*
* Roles:
*
* OWNER_ROLE
* | -> May add or remove addresses from any of the roles below.
* |
* +-- SLASHER_ROLE
* | -> Can slash staked token balances and withdraw those funds.
* |
* +-- EPOCH_PARAMETERS_ROLE
* | -> May set epoch parameters such as the interval, offset, and blackout window.
* |
* +-- REWARDS_RATE_ROLE
* | -> May set the emission rate of rewards.
* |
* +-- CLAIM_OPERATOR_ROLE
* | -> May claim rewards on behalf of a user.
* |
* +-- STAKE_OPERATOR_ROLE
* -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user).
*/
abstract contract SM1Roles is SM1Storage {
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE');
bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE');
bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE');
bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE');
bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE');
function __SM1Roles_init() internal {
// Assign roles to the sender.
//
// The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned.
// These can be assigned to other smart contracts to provide additional functionality for users.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(SLASHER_ROLE, msg.sender);
_setupRole(EPOCH_PARAMETERS_ROLE, msg.sender);
_setupRole(REWARDS_RATE_ROLE, msg.sender);
// Set OWNER_ROLE as the admin of all roles.
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(SLASHER_ROLE, OWNER_ROLE);
_setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE);
_setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE);
_setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE);
_setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Rewards } from './SM1Rewards.sol';
/**
* @title SM1StakedBalances
* @author dYdX
*
* @dev Accounting of staked balances.
*
* NOTE: Functions may revert if epoch zero has not started.
*
* NOTE: All amounts dealt with in this file are denominated in staked units, which because of the
* exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol.
*
* STAKED BALANCE ACCOUNTING:
*
* A staked balance is in one of two states:
* - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed.
* - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed.
*
* A staker may have a combination of active and inactive balances. The following operations
* affect staked balances as follows:
* - deposit: Increase active balance.
* - request withdrawal: At the end of the current epoch, move some active funds to inactive.
* - withdraw: Decrease inactive balance.
* - transfer: Move some active funds to another staker.
*
* To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we
* store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and
* nextEpochBalance.
*
* REWARDS ACCOUNTING:
*
* Active funds earn rewards for the period of time that they remain active. This means, after
* requesting a withdrawal of some funds, those funds will continue to earn rewards until the end
* of the epoch. For example:
*
* epoch: n n + 1 n + 2 n + 3
* | | | |
* +----------+----------+----------+-----...
* ^ t_0: User makes a deposit.
* ^ t_1: User requests a withdrawal of all funds.
* ^ t_2: The funds change state from active to inactive.
*
* In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying
* with the total staked balance in that period. If the user only request a withdrawal for a part
* of their balance, then the remaining balance would continue earning rewards beyond t_2.
*
* User rewards must be settled via SM1Rewards any time a user's active balance changes. Special
* attention is paid to the the epoch boundaries, where funds may have transitioned from active
* to inactive.
*
* SETTLEMENT DETAILS:
*
* Internally, this module uses the following types of operations on stored balances:
* - Load: Loads a balance, while applying settlement logic internally to get the
* up-to-date result. Returns settlement results without updating state.
* - Store: Stores a balance.
* - Load-for-update: Performs a load and applies updates as needed to rewards accounting.
* Since this is state-changing, it must be followed by a store operation.
* - Settle: Performs load-for-update and store operations.
*
* This module is responsible for maintaining the following invariants to ensure rewards are
* calculated correctly:
* - When an active balance is loaded for update, if a rollover occurs from one epoch to the
* next, the rewards index must be settled up to the boundary at which the rollover occurs.
* - Because the global rewards index is needed to update the user rewards index, the total
* active balance must be settled before any staker balances are settled or loaded for update.
* - A staker's balance must be settled before their rewards are settled.
*/
abstract contract SM1StakedBalances is
SM1Rewards
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Constructor ============
constructor(
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{}
// ============ Public Functions ============
/**
* @notice Get the current active balance of a staker.
*/
function getActiveBalanceCurrentEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_ACTIVE_BALANCES_[staker]
);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch active balance of a staker.
*/
function getActiveBalanceNextEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_ACTIVE_BALANCES_[staker]
);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current total active balance.
*/
function getTotalActiveBalanceCurrentEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_TOTAL_ACTIVE_BALANCE_
);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch total active balance.
*/
function getTotalActiveBalanceNextEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_TOTAL_ACTIVE_BALANCE_
);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current inactive balance of a staker.
* @dev The balance is converted via the index to token units.
*/
function getInactiveBalanceCurrentEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch inactive balance of a staker.
* @dev The balance is converted via the index to token units.
*/
function getInactiveBalanceNextEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current total inactive balance.
*/
function getTotalInactiveBalanceCurrentEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch total inactive balance.
*/
function getTotalInactiveBalanceNextEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current transferable balance for a user. The user can
* only transfer their balance that is not currently inactive or going to be
* inactive in the next epoch. Note that this means the user's transferable funds
* are their active balance of the next epoch.
*
* @param account The account to get the transferable balance of.
*
* @return The user's transferable balance.
*/
function getTransferableBalance(
address account
)
public
view
returns (uint256)
{
return getActiveBalanceNextEpoch(account);
}
// ============ Internal Functions ============
function _increaseCurrentAndNextActiveBalance(
address staker,
uint256 amount
)
internal
{
// Always settle total active balance before settling a staker active balance.
uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount);
uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount);
// When an active balance changes at current timestamp, settle rewards to the current timestamp.
_settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance);
}
function _moveNextBalanceActiveToInactive(
address staker,
uint256 amount
)
internal
{
// Decrease the active balance for the next epoch.
// Always settle total active balance before settling a staker active balance.
_decreaseNextBalance(address(0), true, amount);
_decreaseNextBalance(staker, true, amount);
// Increase the inactive balance for the next epoch.
_increaseNextBalance(address(0), false, amount);
_increaseNextBalance(staker, false, amount);
// Note that we don't need to settle rewards since the current active balance did not change.
}
function _transferCurrentAndNextActiveBalance(
address sender,
address recipient,
uint256 amount
)
internal
{
// Always settle total active balance before settling a staker active balance.
uint256 totalBalance = _settleTotalActiveBalance();
// Move current and next active balances from sender to recipient.
uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount);
uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount);
// When an active balance changes at current timestamp, settle rewards to the current timestamp.
_settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance);
_settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance);
}
function _decreaseCurrentAndNextInactiveBalance(
address staker,
uint256 amount
)
internal
{
// Decrease the inactive balance for the next epoch.
_decreaseCurrentAndNextBalances(address(0), false, amount);
_decreaseCurrentAndNextBalances(staker, false, amount);
// Note that we don't settle rewards since active balances are not affected.
}
function _settleTotalActiveBalance()
internal
returns (uint256)
{
return _settleBalance(address(0), true);
}
function _settleAndClaimRewards(
address staker,
address recipient
)
internal
returns (uint256)
{
// Always settle total active balance before settling a staker active balance.
uint256 totalBalance = _settleTotalActiveBalance();
// Always settle staker active balance before settling staker rewards.
uint256 userBalance = _settleBalance(staker, true);
// Settle rewards balance since we want to claim the full accrued amount.
_settleUserRewardsUpToNow(staker, userBalance, totalBalance);
// Claim rewards balance.
return _claimRewards(staker, recipient);
}
// ============ Private Functions ============
/**
* @dev Load a balance for update and then store it.
*/
function _settleBalance(
address maybeStaker,
bool isActiveBalance
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 currentBalance = uint256(balance.currentEpochBalance);
_storeBalance(balancePtr, balance);
return currentBalance;
}
/**
* @dev Settle a balance while applying an increase.
*/
function _increaseCurrentAndNextBalances(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 originalCurrentBalance = uint256(balance.currentEpochBalance);
balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240();
balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240();
_storeBalance(balancePtr, balance);
return originalCurrentBalance;
}
/**
* @dev Settle a balance while applying a decrease.
*/
function _decreaseCurrentAndNextBalances(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 originalCurrentBalance = uint256(balance.currentEpochBalance);
balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240();
balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240();
_storeBalance(balancePtr, balance);
return originalCurrentBalance;
}
/**
* @dev Settle a balance while applying an increase.
*/
function _increaseNextBalance(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240();
_storeBalance(balancePtr, balance);
}
/**
* @dev Settle a balance while applying a decrease.
*/
function _decreaseNextBalance(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240();
_storeBalance(balancePtr, balance);
}
function _getBalancePtr(
address maybeStaker,
bool isActiveBalance
)
private
view
returns (SM1Types.StoredBalance storage)
{
// Active.
if (isActiveBalance) {
if (maybeStaker != address(0)) {
return _ACTIVE_BALANCES_[maybeStaker];
}
return _TOTAL_ACTIVE_BALANCE_;
}
// Inactive.
if (maybeStaker != address(0)) {
return _INACTIVE_BALANCES_[maybeStaker];
}
return _TOTAL_INACTIVE_BALANCE_;
}
/**
* @dev Load a balance for updating.
*
* IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards.
* - For active balances:
* - If a rollover occurs, rewards are settled up to the epoch boundary.
*
* @param balancePtr A storage pointer to the balance.
* @param maybeStaker The user address, or address(0) to update total balance.
* @param isActiveBalance Whether the balance is an active balance.
*/
function _loadBalanceForUpdate(
SM1Types.StoredBalance storage balancePtr,
address maybeStaker,
bool isActiveBalance
)
private
returns (SM1Types.StoredBalance memory)
{
// Active balance.
if (isActiveBalance) {
(
SM1Types.StoredBalance memory balance,
uint256 beforeRolloverEpoch,
uint256 beforeRolloverBalance,
bool didRolloverOccur
) = _loadActiveBalance(balancePtr);
if (didRolloverOccur) {
// Handle the effect of the balance rollover on rewards. We must partially settle the index
// up to the epoch boundary where the change in balance occurred. We pass in the balance
// from before the boundary.
if (maybeStaker == address(0)) {
// If it's the total active balance...
_settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch);
} else {
// If it's a user active balance...
_settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch);
}
}
return balance;
}
// Inactive balance.
return _loadInactiveBalance(balancePtr);
}
function _loadActiveBalance(
SM1Types.StoredBalance storage balancePtr
)
private
view
returns (
SM1Types.StoredBalance memory,
uint256,
uint256,
bool
)
{
SM1Types.StoredBalance memory balance = balancePtr;
// Return these as they may be needed for rewards settlement.
uint256 beforeRolloverEpoch = uint256(balance.currentEpoch);
uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance);
bool didRolloverOccur = false;
// Roll the balance forward if needed.
uint256 currentEpoch = getCurrentEpoch();
if (currentEpoch > uint256(balance.currentEpoch)) {
didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance;
balance.currentEpoch = currentEpoch.toUint16();
balance.currentEpochBalance = balance.nextEpochBalance;
}
return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur);
}
function _loadInactiveBalance(
SM1Types.StoredBalance storage balancePtr
)
private
view
returns (SM1Types.StoredBalance memory)
{
SM1Types.StoredBalance memory balance = balancePtr;
// Roll the balance forward if needed.
uint256 currentEpoch = getCurrentEpoch();
if (currentEpoch > uint256(balance.currentEpoch)) {
balance.currentEpoch = currentEpoch.toUint16();
balance.currentEpochBalance = balance.nextEpochBalance;
}
return balance;
}
/**
* @dev Store a balance.
*/
function _storeBalance(
SM1Types.StoredBalance storage balancePtr,
SM1Types.StoredBalance memory balance
)
private
{
// Note: This should use a single `sstore` when compiler optimizations are enabled.
balancePtr.currentEpoch = balance.currentEpoch;
balancePtr.currentEpochBalance = balance.currentEpochBalance;
balancePtr.nextEpochBalance = balance.nextEpochBalance;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
import { SM1Types } from '../lib/SM1Types.sol';
/**
* @title SM1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contract with storage.
*/
abstract contract SM1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Epoch Schedule ============
/// @dev The parameters specifying the function from timestamp to epoch number.
SM1Types.EpochParameters internal _EPOCH_PARAMETERS_;
/// @dev The period of time at the end of each epoch in which withdrawals cannot be requested.
uint256 internal _BLACKOUT_WINDOW_;
// ============ Staked Token ERC20 ============
/// @dev Allowances for ERC-20 transfers.
mapping(address => mapping(address => uint256)) internal _ALLOWANCES_;
// ============ Governance Power Delegation ============
/// @dev Domain separator for EIP-712 signatures.
bytes32 internal _DOMAIN_SEPARATOR_;
/// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures.
mapping(address => uint256) internal _NONCES_;
/// @dev Snapshots and delegates for governance voting power.
mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_;
mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_;
mapping(address => address) internal _VOTING_DELEGATES_;
/// @dev Snapshots and delegates for governance proposition power.
mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_;
mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_;
mapping(address => address) internal _PROPOSITION_DELEGATES_;
// ============ Rewards Accounting ============
/// @dev The emission rate of rewards.
uint256 internal _REWARDS_PER_SECOND_;
/// @dev The cumulative rewards earned per staked token. (Shared storage slot.)
uint224 internal _GLOBAL_INDEX_;
/// @dev The timestamp at which the global index was last updated. (Shared storage slot.)
uint32 internal _GLOBAL_INDEX_TIMESTAMP_;
/// @dev The value of the global index when the user's staked balance was last updated.
mapping(address => uint256) internal _USER_INDEXES_;
/// @dev The user's accrued, unclaimed rewards (as of the last update to the user index).
mapping(address => uint256) internal _USER_REWARDS_BALANCES_;
/// @dev The value of the global index at the end of a given epoch.
mapping(uint256 => uint256) internal _EPOCH_INDEXES_;
// ============ Staker Accounting ============
/// @dev The active balance by staker.
mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_;
/// @dev The total active balance of stakers.
SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_;
/// @dev The inactive balance by staker.
mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_;
/// @dev The total inactive balance of stakers.
SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_;
// ============ Exchange Rate ============
/// @dev The value of one underlying token, in the units used for staked balances, denominated
/// as a mutiple of EXCHANGE_RATE_BASE for additional precision.
uint256 internal _EXCHANGE_RATE_;
/// @dev Historical snapshots of the exchange rate, in each block that it has changed.
mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_;
/// @dev Number of snapshots of the exchange rate.
uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) 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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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(IAccessControlUpgradeable).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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 granted `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}.
* ====
*/
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, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = '0123456789abcdef';
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, 'Strings: hex length insufficient');
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './IERC165.sol';
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @dev Methods for downcasting unsigned integers, reverting on overflow.
*/
library SafeCast {
/**
* @dev Downcast to a uint16, reverting on overflow.
*/
function toUint16(
uint256 a
)
internal
pure
returns (uint16)
{
uint16 b = uint16(a);
require(
uint256(b) == a,
'SafeCast: toUint16 overflow'
);
return b;
}
/**
* @dev Downcast to a uint32, reverting on overflow.
*/
function toUint32(
uint256 a
)
internal
pure
returns (uint32)
{
uint32 b = uint32(a);
require(
uint256(b) == a,
'SafeCast: toUint32 overflow'
);
return b;
}
/**
* @dev Downcast to a uint128, reverting on overflow.
*/
function toUint128(
uint256 a
)
internal
pure
returns (uint128)
{
uint128 b = uint128(a);
require(
uint256(b) == a,
'SafeCast: toUint128 overflow'
);
return b;
}
/**
* @dev Downcast to a uint224, reverting on overflow.
*/
function toUint224(
uint256 a
)
internal
pure
returns (uint224)
{
uint224 b = uint224(a);
require(
uint256(b) == a,
'SafeCast: toUint224 overflow'
);
return b;
}
/**
* @dev Downcast to a uint240, reverting on overflow.
*/
function toUint240(
uint256 a
)
internal
pure
returns (uint240)
{
uint240 b = uint240(a);
require(
uint256(b) == a,
'SafeCast: toUint240 overflow'
);
return b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1EpochSchedule } from './SM1EpochSchedule.sol';
/**
* @title SM1Rewards
* @author dYdX
*
* @dev Manages the distribution of token rewards.
*
* Rewards are distributed continuously. After each second, an account earns rewards `r` according
* to the following formula:
*
* r = R * s / S
*
* Where:
* - `R` is the rewards distributed globally each second, also called the “emission rate.”
* - `s` is the account's staked balance in that second (technically, it is measured at the
* end of the second)
* - `S` is the sum total of all staked balances in that second (again, measured at the end of
* the second)
*
* The parameter `R` can be configured by the contract owner. For every second that elapses,
* exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that
* while the total staked balance is zero, no tokens will accrue to anyone.
*
* The accounting works as follows: A global index is stored which represents the cumulative
* number of rewards tokens earned per staked token since the start of the distribution.
* The value of this index increases over time, and there are two factors affecting the rate of
* increase:
* 1) The emission rate (in the numerator)
* 2) The total number of staked tokens (in the denominator)
*
* Whenever either factor changes, in some timestamp T, we settle the global index up to T by
* calculating the increase in the index since the last update using the OLD values of the factors:
*
* indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked
*
* Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index.
*
* For each user we store an accrued rewards balance, as well as a user index, which is a cache of
* the global index at the time that the user's accrued rewards balance was last updated. Then at
* any point in time, a user's claimable rewards are represented by the following:
*
* rewards = _USER_REWARDS_BALANCES_[user] + userStaked * (
* settledGlobalIndex - _USER_INDEXES_[user]
* ) / INDEX_BASE
*/
abstract contract SM1Rewards is
SM1EpochSchedule
{
using SafeCast for uint256;
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @dev Additional precision used to represent the global and user index values.
uint256 private constant INDEX_BASE = 10**18;
/// @notice The rewards token.
IERC20 public immutable REWARDS_TOKEN;
/// @notice Address to pull rewards from. Must have provided an allowance to this contract.
address public immutable REWARDS_TREASURY;
/// @notice Start timestamp (inclusive) of the period in which rewards can be earned.
uint256 public immutable DISTRIBUTION_START;
/// @notice End timestamp (exclusive) of the period in which rewards can be earned.
uint256 public immutable DISTRIBUTION_END;
// ============ Events ============
event RewardsPerSecondUpdated(
uint256 emissionPerSecond
);
event GlobalIndexUpdated(
uint256 index
);
event UserIndexUpdated(
address indexed user,
uint256 index,
uint256 unclaimedRewards
);
event ClaimedRewards(
address indexed user,
address recipient,
uint256 claimedRewards
);
// ============ Constructor ============
constructor(
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
) {
require(
distributionEnd >= distributionStart,
'SM1Rewards: Invalid parameters'
);
REWARDS_TOKEN = rewardsToken;
REWARDS_TREASURY = rewardsTreasury;
DISTRIBUTION_START = distributionStart;
DISTRIBUTION_END = distributionEnd;
}
// ============ External Functions ============
/**
* @notice The current emission rate of rewards.
*
* @return The number of rewards tokens issued globally each second.
*/
function getRewardsPerSecond()
external
view
returns (uint256)
{
return _REWARDS_PER_SECOND_;
}
// ============ Internal Functions ============
/**
* @dev Initialize the contract.
*/
function __SM1Rewards_init()
internal
{
_GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32();
}
/**
* @dev Set the emission rate of rewards.
*
* IMPORTANT: Do not call this function without settling the total staked balance first, to
* ensure that the index is settled up to the epoch boundaries.
*
* @param emissionPerSecond The new number of rewards tokens to give out each second.
* @param totalStaked The total staked balance.
*/
function _setRewardsPerSecond(
uint256 emissionPerSecond,
uint256 totalStaked
)
internal
{
_settleGlobalIndexUpToNow(totalStaked);
_REWARDS_PER_SECOND_ = emissionPerSecond;
emit RewardsPerSecondUpdated(emissionPerSecond);
}
/**
* @dev Claim tokens, sending them to the specified recipient.
*
* Note: In order to claim all accrued rewards, the total and user staked balances must first be
* settled before calling this function.
*
* @param user The user's address.
* @param recipient The address to send rewards to.
*
* @return The number of rewards tokens claimed.
*/
function _claimRewards(
address user,
address recipient
)
internal
returns (uint256)
{
uint256 accruedRewards = _USER_REWARDS_BALANCES_[user];
_USER_REWARDS_BALANCES_[user] = 0;
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards);
emit ClaimedRewards(user, recipient, accruedRewards);
return accruedRewards;
}
/**
* @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a
* settlement of the global index up to `block.timestamp`. Should be called with the OLD user
* and total balances.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user during the period since the last user index
* update.
* @param totalStaked Total tokens staked by all users during the period since the last global
* index update.
*
* @return The user's accrued rewards, including past unclaimed rewards.
*/
function _settleUserRewardsUpToNow(
address user,
uint256 userStaked,
uint256 totalStaked
)
internal
returns (uint256)
{
uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked);
return _settleUserRewardsUpToIndex(user, userStaked, globalIndex);
}
/**
* @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a
* user's rewards if their balance was known to have changed on that epoch boundary.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user. Should be accurate for the time period
* since the last update to this user and up to the end of the
* specified epoch.
* @param epochNumber Settle the user's rewards up to the end of this epoch.
*
* @return The user's accrued rewards, including past unclaimed rewards, up to the end of the
* specified epoch.
*/
function _settleUserRewardsUpToEpoch(
address user,
uint256 userStaked,
uint256 epochNumber
)
internal
returns (uint256)
{
uint256 globalIndex = _EPOCH_INDEXES_[epochNumber];
return _settleUserRewardsUpToIndex(user, userStaked, globalIndex);
}
/**
* @dev Settle the global index up to the end of the given epoch.
*
* IMPORTANT: This function should only be called under conditions which ensure the following:
* - `epochNumber` < the current epoch number
* - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp`
* - `_EPOCH_INDEXES_[epochNumber] = 0`
*/
function _settleGlobalIndexUpToEpoch(
uint256 totalStaked,
uint256 epochNumber
)
internal
returns (uint256)
{
uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1));
uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp);
_EPOCH_INDEXES_[epochNumber] = globalIndex;
return globalIndex;
}
// ============ Private Functions ============
/**
* @dev Updates the global index, reflecting cumulative rewards given out per staked token.
*
* @param totalStaked The total staked balance, which should be constant in the interval
* since the last update to the global index.
*
* @return The new global index.
*/
function _settleGlobalIndexUpToNow(
uint256 totalStaked
)
private
returns (uint256)
{
return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp);
}
/**
* @dev Helper function which settles a user's rewards up to a global index. Should be called
* any time a user's staked balance changes, with the OLD user and total balances.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user during the period since the last user index
* update.
* @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less
* than the user's index.
*
* @return The user's accrued rewards, including past unclaimed rewards.
*/
function _settleUserRewardsUpToIndex(
address user,
uint256 userStaked,
uint256 newGlobalIndex
)
private
returns (uint256)
{
uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user];
uint256 oldUserIndex = _USER_INDEXES_[user];
if (oldUserIndex == newGlobalIndex) {
return oldAccruedRewards;
}
uint256 newAccruedRewards;
if (userStaked == 0) {
// Note: Even if the user's staked balance is zero, we still need to update the user index.
newAccruedRewards = oldAccruedRewards;
} else {
// Calculate newly accrued rewards since the last update to the user's index.
uint256 indexDelta = newGlobalIndex.sub(oldUserIndex);
uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE);
newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta);
// Update the user's rewards.
_USER_REWARDS_BALANCES_[user] = newAccruedRewards;
}
// Update the user's index.
_USER_INDEXES_[user] = newGlobalIndex;
emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards);
return newAccruedRewards;
}
/**
* @dev Updates the global index, reflecting cumulative rewards given out per staked token.
*
* @param totalStaked The total staked balance, which should be constant in the interval
* (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp).
* @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy
* `settleUpToTimestamp <= block.timestamp`.
*
* @return The new global index.
*/
function _settleGlobalIndexUpToTimestamp(
uint256 totalStaked,
uint256 settleUpToTimestamp
)
private
returns (uint256)
{
uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_);
// The goal of this function is to calculate rewards earned since the last global index update.
// These rewards are earned over the time interval which is the intersection of the intervals
// [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END].
//
// We can simplify a bit based on the assumption:
// `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START`
//
// Get the start and end of the time interval under consideration.
uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_);
uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END);
// Return early if the interval has length zero (incl. case where intervalEnd < intervalStart).
if (intervalEnd <= intervalStart) {
return oldGlobalIndex;
}
// Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_.
uint256 emissionPerSecond = _REWARDS_PER_SECOND_;
if (emissionPerSecond == 0 || totalStaked == 0) {
// Ensure a log is emitted if the timestamp changed, even if the index does not change.
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
emit GlobalIndexUpdated(oldGlobalIndex);
return oldGlobalIndex;
}
// Calculate the change in index over the interval.
uint256 timeDelta = intervalEnd.sub(intervalStart);
uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked);
// Calculate, update, and return the new global index.
uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta);
// Update storage. (Shared storage slot.)
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
_GLOBAL_INDEX_ = newGlobalIndex.toUint224();
emit GlobalIndexUpdated(newGlobalIndex);
return newGlobalIndex;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1EpochSchedule
* @author dYdX
*
* @dev Defines a function from block timestamp to epoch number.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*
* Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch
* zero starts at a non-negative timestamp.
*
* The recommended epoch length and blackout window are 28 and 7 days respectively; however, these
* are modifiable by the admin, within the specified bounds.
*/
abstract contract SM1EpochSchedule is
SM1Storage
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Events ============
event EpochParametersChanged(
SM1Types.EpochParameters epochParameters
);
event BlackoutWindowChanged(
uint256 blackoutWindow
);
// ============ Initializer ============
function __SM1EpochSchedule_init(
uint256 interval,
uint256 offset,
uint256 blackoutWindow
)
internal
{
require(
block.timestamp < offset,
'SM1EpochSchedule: Epoch zero must start after initialization'
);
_setBlackoutWindow(blackoutWindow);
_setEpochParameters(interval, offset);
}
// ============ Public Functions ============
/**
* @notice Get the epoch at the current block timestamp.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The current epoch number.
*/
function getCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
return offsetTimestamp.div(interval);
}
/**
* @notice Get the time remaining in the current epoch.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The number of seconds until the next epoch.
*/
function getTimeRemainingInCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval);
return interval.sub(timeElapsedInEpoch);
}
/**
* @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`.
*
* @return The timestamp in seconds representing the start of that epoch.
*/
function getStartOfEpoch(
uint256 epochNumber
)
public
view
returns (uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
return epochNumber.mul(interval).add(offset);
}
/**
* @notice Check whether we are at or past the start of epoch zero.
*
* @return Boolean `true` if the current timestamp is at least the start of epoch zero,
* otherwise `false`.
*/
function hasEpochZeroStarted()
public
view
returns (bool)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 offset = uint256(epochParameters.offset);
return block.timestamp >= offset;
}
/**
* @notice Check whether we are in a blackout window, where withdrawal requests are restricted.
* Note that before epoch zero has started, there are no blackout windows.
*
* @return Boolean `true` if we are in a blackout window, otherwise `false`.
*/
function inBlackoutWindow()
public
view
returns (bool)
{
return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_;
}
// ============ Internal Functions ============
function _setEpochParameters(
uint256 interval,
uint256 offset
)
internal
{
SM1Types.EpochParameters memory epochParameters =
SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()});
_EPOCH_PARAMETERS_ = epochParameters;
emit EpochParametersChanged(epochParameters);
}
function _setBlackoutWindow(
uint256 blackoutWindow
)
internal
{
_BLACKOUT_WINDOW_ = blackoutWindow;
emit BlackoutWindowChanged(blackoutWindow);
}
// ============ Private Functions ============
/**
* @dev Helper function to read params from storage and apply offset to the given timestamp.
* Recall that the formula for epoch number is `n = (t - b) / a`.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The values `a` and `(t - b)`.
*/
function _getIntervalAndOffsetTimestamp()
private
view
returns (uint256, uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
require(
block.timestamp >= offset,
'SM1EpochSchedule: Epoch zero has not started'
);
uint256 offsetTimestamp = block.timestamp.sub(offset);
return (interval, offsetTimestamp);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1ERC20
* @author dYdX
*
* @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens.
*
* Also allows a user with an active stake to transfer their staked tokens to another user,
* even if they would otherwise be restricted from withdrawing.
*/
abstract contract SM1ERC20 is
SM1StakedBalances,
SM1GovernancePowerDelegation,
IERC20Detailed
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice EIP-712 typehash for token approval via EIP-2612 permit.
bytes32 public constant PERMIT_TYPEHASH = keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
// ============ External Functions ============
function name()
external
pure
override
returns (string memory)
{
return 'Staked DYDX';
}
function symbol()
external
pure
override
returns (string memory)
{
return 'stkDYDX';
}
function decimals()
external
pure
override
returns (uint8)
{
return 18;
}
/**
* @notice Get the total supply of staked balances.
*
* Note that due to the exchange rate, this is different than querying the total balance of
* underyling token staked to this contract.
*
* @return The sum of all staked balances.
*/
function totalSupply()
external
view
override
returns (uint256)
{
return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch();
}
/**
* @notice Get a user's staked balance.
*
* Note that due to the exchange rate, one unit of staked balance may not be equivalent to one
* unit of the underlying token. Also note that a user's staked balance is different from a
* user's transferable balance.
*
* @param account The account to get the balance of.
*
* @return The user's staked balance.
*/
function balanceOf(
address account
)
public
view
override(SM1GovernancePowerDelegation, IERC20)
returns (uint256)
{
return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account);
}
function transfer(
address recipient,
uint256 amount
)
external
override
nonReentrant
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(
address owner,
address spender
)
external
view
override
returns (uint256)
{
return _ALLOWANCES_[owner][spender];
}
function approve(
address spender,
uint256 amount
)
external
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
)
external
override
nonReentrant
returns (bool)
{
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance')
);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
_approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
_approve(
msg.sender,
spender,
_ALLOWANCES_[msg.sender][spender].sub(
subtractedValue,
'SM1ERC20: Decreased allowance below zero'
)
);
return true;
}
/**
* @notice Implements the permit function as specified in EIP-2612.
*
* @param owner Address of the token owner.
* @param spender Address of the spender.
* @param value Amount of allowance.
* @param deadline Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(
owner != address(0),
'SM1ERC20: INVALID_OWNER'
);
require(
block.timestamp <= deadline,
'SM1ERC20: INVALID_EXPIRATION'
);
uint256 currentValidNonce = _NONCES_[owner];
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
_DOMAIN_SEPARATOR_,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
)
);
require(
owner == ecrecover(digest, v, r, s),
'SM1ERC20: INVALID_SIGNATURE'
);
_NONCES_[owner] = currentValidNonce.add(1);
_approve(owner, spender, value);
}
// ============ Internal Functions ============
function _transfer(
address sender,
address recipient,
uint256 amount
)
internal
{
require(
sender != address(0),
'SM1ERC20: Transfer from address(0)'
);
require(
recipient != address(0),
'SM1ERC20: Transfer to address(0)'
);
require(
getTransferableBalance(sender) >= amount,
'SM1ERC20: Transfer exceeds next epoch active balance'
);
// Update staked balances and delegate snapshots.
_transferCurrentAndNextActiveBalance(sender, recipient, amount);
_moveDelegatesForTransfer(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
)
internal
{
require(
owner != address(0),
'SM1ERC20: Approve from address(0)'
);
require(
spender != address(0),
'SM1ERC20: Approve to address(0)'
);
_ALLOWANCES_[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
import { IERC20 } from './IERC20.sol';
/**
* @dev Interface for ERC20 including metadata
**/
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import {
IGovernancePowerDelegationERC20
} from '../../../interfaces/IGovernancePowerDelegationERC20.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1ExchangeRate } from './SM1ExchangeRate.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1GovernancePowerDelegation
* @author dYdX
*
* @dev Provides support for two types of governance powers which are separately delegatable.
* Provides functions for delegation and for querying a user's power at a certain block number.
*
* Internally, makes use of staked balances denoted in staked units, but returns underlying token
* units from the getPowerAtBlock() and getPowerCurrent() functions.
*
* This is based on, and is designed to match, Aave's implementation, which is used in their
* governance token and staked token contracts.
*/
abstract contract SM1GovernancePowerDelegation is
SM1ExchangeRate,
IGovernancePowerDelegationERC20
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice EIP-712 typehash for delegation by signature of a specific governance power type.
bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256(
'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)'
);
/// @notice EIP-712 typehash for delegation by signature of all governance powers.
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
'Delegate(address delegatee,uint256 nonce,uint256 expiry)'
);
// ============ External Functions ============
/**
* @notice Delegates a specific governance power of the sender to a delegatee.
*
* @param delegatee The address to delegate power to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function delegateByType(
address delegatee,
DelegationType delegationType
)
external
override
{
_delegateByType(msg.sender, delegatee, delegationType);
}
/**
* @notice Delegates all governance powers of the sender to a delegatee.
*
* @param delegatee The address to delegate power to.
*/
function delegate(
address delegatee
)
external
override
{
_delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER);
_delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER);
}
/**
* @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature.
*
* @param delegatee The address to delegate votes to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
* @param nonce The signer's nonce for EIP-712 signatures on this contract.
* @param expiry Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function delegateByTypeBySig(
address delegatee,
DelegationType delegationType,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(
abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry)
);
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash));
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0),
'SM1GovernancePowerDelegation: INVALID_SIGNATURE'
);
require(
nonce == _NONCES_[signer]++,
'SM1GovernancePowerDelegation: INVALID_NONCE'
);
require(
block.timestamp <= expiry,
'SM1GovernancePowerDelegation: INVALID_EXPIRATION'
);
_delegateByType(signer, delegatee, delegationType);
}
/**
* @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature.
*
* @param delegatee The address to delegate votes to.
* @param nonce The signer's nonce for EIP-712 signatures on this contract.
* @param expiry Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash));
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0),
'SM1GovernancePowerDelegation: INVALID_SIGNATURE'
);
require(
nonce == _NONCES_[signer]++,
'SM1GovernancePowerDelegation: INVALID_NONCE'
);
require(
block.timestamp <= expiry,
'SM1GovernancePowerDelegation: INVALID_EXPIRATION'
);
_delegateByType(signer, delegatee, DelegationType.VOTING_POWER);
_delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER);
}
/**
* @notice Returns the delegatee of a user.
*
* @param delegator The address of the delegator.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function getDelegateeByType(
address delegator,
DelegationType delegationType
)
external
override
view
returns (address)
{
(, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);
return _getDelegatee(delegator, delegates);
}
/**
* @notice Returns the current power of a user. The current power is the power delegated
* at the time of the last snapshot.
*
* @param user The user whose power to query.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerCurrent(
address user,
DelegationType delegationType
)
external
override
view
returns (uint256)
{
return getPowerAtBlock(user, block.number, delegationType);
}
/**
* @notice Get the next valid nonce for EIP-712 signatures.
*
* This nonce should be used when signing for any of the following functions:
* - permit()
* - delegateByTypeBySig()
* - delegateBySig()
*/
function nonces(
address owner
)
external
view
returns (uint256)
{
return _NONCES_[owner];
}
// ============ Public Functions ============
function balanceOf(
address account
)
public
view
virtual
returns (uint256);
/**
* @notice Returns the power of a user at a certain block, denominated in underlying token units.
*
* @param user The user whose power to query.
* @param blockNumber The block number at which to get the user's power.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*
* @return The user's governance power of the specified type, in underlying token units.
*/
function getPowerAtBlock(
address user,
uint256 blockNumber,
DelegationType delegationType
)
public
override
view
returns (uint256)
{
(
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots,
mapping(address => uint256) storage snapshotCounts,
// unused: delegates
) = _getDelegationDataByType(delegationType);
uint256 stakeAmount = _findValueAtBlock(
snapshots[user],
snapshotCounts[user],
blockNumber,
0
);
uint256 exchangeRate = _findValueAtBlock(
_EXCHANGE_RATE_SNAPSHOTS_,
_EXCHANGE_RATE_SNAPSHOT_COUNT_,
blockNumber,
EXCHANGE_RATE_BASE
);
return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate);
}
// ============ Internal Functions ============
/**
* @dev Delegates one specific power to a delegatee.
*
* @param delegator The user whose power to delegate.
* @param delegatee The address to delegate power to.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function _delegateByType(
address delegator,
address delegatee,
DelegationType delegationType
)
internal
{
require(
delegatee != address(0),
'SM1GovernancePowerDelegation: INVALID_DELEGATEE'
);
(, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);
uint256 delegatorBalance = balanceOf(delegator);
address previousDelegatee = _getDelegatee(delegator, delegates);
delegates[delegator] = delegatee;
_moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType);
emit DelegateChanged(delegator, delegatee, delegationType);
}
/**
* @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned.
*
* @param from The sender.
* @param to The recipient.
* @param stakedAmount The amount being transfered, denominated in staked units.
*/
function _moveDelegatesForTransfer(
address from,
address to,
uint256 stakedAmount
)
internal
{
address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_);
address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_);
_moveDelegatesByType(
votingPowerFromDelegatee,
votingPowerToDelegatee,
stakedAmount,
DelegationType.VOTING_POWER
);
address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_);
address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_);
_moveDelegatesByType(
propositionPowerFromDelegatee,
propositionPowerToDelegatee,
stakedAmount,
DelegationType.PROPOSITION_POWER
);
}
/**
* @dev Moves power from one user to another.
*
* @param from The user from which delegated power is moved.
* @param to The user that will receive the delegated power.
* @param amount The amount of power to be moved.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function _moveDelegatesByType(
address from,
address to,
uint256 amount,
DelegationType delegationType
)
internal
{
if (from == to) {
return;
}
(
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots,
mapping(address => uint256) storage snapshotCounts,
// unused: delegates
) = _getDelegationDataByType(delegationType);
if (from != address(0)) {
mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from];
uint256 fromSnapshotCount = snapshotCounts[from];
uint256 previousBalance = 0;
if (fromSnapshotCount != 0) {
previousBalance = fromSnapshots[fromSnapshotCount - 1].value;
}
uint256 newBalance = previousBalance.sub(amount);
snapshotCounts[from] = _writeSnapshot(
fromSnapshots,
fromSnapshotCount,
newBalance
);
emit DelegatedPowerChanged(from, newBalance, delegationType);
}
if (to != address(0)) {
mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to];
uint256 toSnapshotCount = snapshotCounts[to];
uint256 previousBalance = 0;
if (toSnapshotCount != 0) {
previousBalance = toSnapshots[toSnapshotCount - 1].value;
}
uint256 newBalance = previousBalance.add(amount);
snapshotCounts[to] = _writeSnapshot(
toSnapshots,
toSnapshotCount,
newBalance
);
emit DelegatedPowerChanged(to, newBalance, delegationType);
}
}
/**
* @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type.
*
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*
* @return The mapping of each user to a mapping of snapshots.
* @return The mapping of each user to the total number of snapshots for that user.
* @return The mapping of each user to the user's delegate.
*/
function _getDelegationDataByType(
DelegationType delegationType
)
internal
view
returns (
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage,
mapping(address => uint256) storage,
mapping(address => address) storage
)
{
if (delegationType == DelegationType.VOTING_POWER) {
return (
_VOTING_SNAPSHOTS_,
_VOTING_SNAPSHOT_COUNTS_,
_VOTING_DELEGATES_
);
} else {
return (
_PROPOSITION_SNAPSHOTS_,
_PROPOSITION_SNAPSHOT_COUNTS_,
_PROPOSITION_DELEGATES_
);
}
}
/**
* @dev Returns the delegatee of a user. If a user never performed any delegation, their
* delegated address will be 0x0, in which case we return the user's own address.
*
* @param delegator The address of the user for which return the delegatee.
* @param delegates The mapping of delegates for a particular type of delegation.
*/
function _getDelegatee(
address delegator,
mapping(address => address) storage delegates
)
internal
view
returns (address)
{
address previousDelegatee = delegates[delegator];
if (previousDelegatee == address(0)) {
return delegator;
}
return previousDelegatee;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
interface IGovernancePowerDelegationERC20 {
enum DelegationType {
VOTING_POWER,
PROPOSITION_POWER
}
/**
* @dev Emitted when a user delegates governance power to another user.
*
* @param delegator The delegator.
* @param delegatee The delegatee.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
event DelegateChanged(
address indexed delegator,
address indexed delegatee,
DelegationType delegationType
);
/**
* @dev Emitted when an action changes the delegated power of a user.
*
* @param user The user whose delegated power has changed.
* @param amount The new amount of delegated power for the user.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType);
/**
* @dev Delegates a specific governance power to a delegatee.
*
* @param delegatee The address to delegate power to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function delegateByType(address delegatee, DelegationType delegationType) external virtual;
/**
* @dev Delegates all governance powers to a delegatee.
*
* @param delegatee The user to which the power will be delegated.
*/
function delegate(address delegatee) external virtual;
/**
* @dev Returns the delegatee of an user.
*
* @param delegator The address of the delegator.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function getDelegateeByType(address delegator, DelegationType delegationType)
external
view
virtual
returns (address);
/**
* @dev Returns the current delegated power of a user. The current power is the power delegated
* at the time of the last snapshot.
*
* @param user The user whose power to query.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerCurrent(address user, DelegationType delegationType)
external
view
virtual
returns (uint256);
/**
* @dev Returns the delegated power of a user at a certain block.
*
* @param user The user whose power to query.
* @param blockNumber The block number at which to get the user's power.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerAtBlock(
address user,
uint256 blockNumber,
DelegationType delegationType
)
external
view
virtual
returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Snapshots } from './SM1Snapshots.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1ExchangeRate
* @author dYdX
*
* @dev Performs math using the exchange rate, which converts between underlying units of the token
* that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract
* for all staked balances (e.g. this.balanceOf(account)).
*
* OVERVIEW:
*
* The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of
* staked balance units that each unit of underlying token is worth. Before any slashes have
* occurred, the exchange rate is equal to one. The exchange rate can increase with each slash,
* indicating that staked balances are becoming less and less valuable, per unit, relative to the
* underlying token.
*
* AVOIDING OVERFLOW AND UNDERFLOW:
*
* Staked balances are represented internally as uint240, so the result of an operation returning
* a staked balances must return a value less than 2^240. Intermediate values in calcuations are
* represented as uint256, so all operations within a calculation must return values under 2^256.
*
* In the functions below operating on the exchange rate, we are strategic in our choice of the
* order of multiplication and division operations, in order to avoid both overflow and underflow.
*
* We use the following assumptions and principles to implement this module:
* - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28.
* - If the exchange rate is greater than 10^46, then we may perform division on the exchange
* rate before performing multiplication, provided that the denominator is not greater
* than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically,
* we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46.
* - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a
* staked balance can never overflow (using the assumption above).
*/
abstract contract SM1ExchangeRate is
SM1Snapshots,
SM1Storage
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice The assumed upper bound on the total supply of the staked token.
uint256 public constant MAX_UNDERLYING_BALANCE = 1e28;
/// @notice Base unit used to represent the exchange rate, for additional precision.
uint256 public constant EXCHANGE_RATE_BASE = 1e18;
/// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance.
/// @dev Approximately 1.2e49
uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE;
/// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE.
/// @dev Approximately 1.2e59
uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE;
/// @notice Max exchange rate.
/// @dev Approximately 1.8e62
uint256 public constant MAX_EXCHANGE_RATE = (
((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE
);
// ============ Initializer ============
function __SM1ExchangeRate_init()
internal
{
_EXCHANGE_RATE_ = EXCHANGE_RATE_BASE;
}
function stakeAmountFromUnderlyingAmount(
uint256 underlyingAmount
)
internal
view
returns (uint256)
{
uint256 exchangeRate = _EXCHANGE_RATE_;
if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) {
uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE);
return underlyingAmount.mul(exchangeRateUnbased);
} else {
return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE);
}
}
function underlyingAmountFromStakeAmount(
uint256 stakeAmount
)
internal
view
returns (uint256)
{
return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_);
}
function underlyingAmountFromStakeAmountWithExchangeRate(
uint256 stakeAmount,
uint256 exchangeRate
)
internal
pure
returns (uint256)
{
if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) {
// Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW.
uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE);
return stakeAmount.div(exchangeRateUnbased);
} else {
return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate);
}
}
function updateExchangeRate(
uint256 numerator,
uint256 denominator
)
internal
returns (uint256)
{
uint256 oldExchangeRate = _EXCHANGE_RATE_;
// Avoid overflow.
// Note that the numerator and denominator are both denominated in underlying token units.
uint256 newExchangeRate;
if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) {
newExchangeRate = oldExchangeRate.div(denominator).mul(numerator);
} else {
newExchangeRate = oldExchangeRate.mul(numerator).div(denominator);
}
require(
newExchangeRate <= MAX_EXCHANGE_RATE,
'SM1ExchangeRate: Max exchange rate exceeded'
);
_EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot(
_EXCHANGE_RATE_SNAPSHOTS_,
_EXCHANGE_RATE_SNAPSHOT_COUNT_,
newExchangeRate
);
_EXCHANGE_RATE_ = newExchangeRate;
return newExchangeRate;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Snapshots
* @author dYdX
*
* @dev Handles storage and retrieval of historical values by block number.
*
* Note that the snapshot stored at a given block number represents the value as of the end of
* that block.
*/
abstract contract SM1Snapshots {
/**
* @dev Writes a snapshot of a value at the current block.
*
* @param snapshots Storage mapping from snapshot index to snapshot struct.
* @param snapshotCount The total number of snapshots in the provided mapping.
* @param newValue The new value to snapshot at the current block.
*
* @return The new snapshot count.
*/
function _writeSnapshot(
mapping(uint256 => SM1Types.Snapshot) storage snapshots,
uint256 snapshotCount,
uint256 newValue
)
internal
returns (uint256)
{
uint256 currentBlock = block.number;
if (
snapshotCount != 0 &&
snapshots[snapshotCount - 1].blockNumber == currentBlock
) {
// If there was a previous snapshot for this block, overwrite it.
snapshots[snapshotCount - 1].value = newValue;
return snapshotCount;
} else {
snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue);
return snapshotCount + 1;
}
}
/**
* @dev Search for the snapshot value at a given block. Uses binary search.
*
* Reverts if `blockNumber` is greater than the current block number.
*
* @param snapshots Storage mapping from snapshot index to snapshot struct.
* @param snapshotCount The total number of snapshots in the provided mapping.
* @param blockNumber The block number to search for.
* @param initialValue The value to return if `blockNumber` is before the earliest snapshot.
*
* @return The snapshot value at the specified block number.
*/
function _findValueAtBlock(
mapping(uint256 => SM1Types.Snapshot) storage snapshots,
uint256 snapshotCount,
uint256 blockNumber,
uint256 initialValue
)
internal
view
returns (uint256)
{
require(
blockNumber <= block.number,
'SM1Snapshots: INVALID_BLOCK_NUMBER'
);
if (snapshotCount == 0) {
return initialValue;
}
// Check earliest snapshot.
if (blockNumber < snapshots[0].blockNumber) {
return initialValue;
}
// Check latest snapshot.
if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) {
return snapshots[snapshotCount - 1].value;
}
uint256 lower = 0;
uint256 upper = snapshotCount - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow.
SM1Types.Snapshot memory snapshot = snapshots[center];
if (snapshot.blockNumber == blockNumber) {
return snapshot.value;
} else if (snapshot.blockNumber < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return snapshots[lower].value;
}
}
|
Claim rewards on behalf of a staker, and send them to the specified recipient. staker The staker whose rewards to claim. recipient The address that should receive the funds. return The number of rewards tokens claimed./
|
function claimRewardsFor(
address staker,
address recipient
)
external
onlyRole(CLAIM_OPERATOR_ROLE)
nonReentrant
returns (uint256)
{
emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender);
return rewards;
}
| 203,832
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAOCurrency
*/
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) {
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string _name,
address _originId,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Position
*/
contract Position is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 4;
uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4);
uint256 public totalSupply;
// Mapping from Name ID to bool value whether or not it has received Position Token
mapping (address => bool) public receivedToken;
// Mapping from Name ID to its total available balance
mapping (address => uint256) public balanceOf;
// Mapping from Name's TAO ID to its staked amount
mapping (address => mapping(address => uint256)) public taoStakedBalance;
// Mapping from TAO ID to its total staked amount
mapping (address => uint256) public totalTAOStakedBalance;
// This generates a public event on the blockchain that will notify clients
event Mint(address indexed nameId, uint256 value);
event Stake(address indexed nameId, address indexed taoId, uint256 value);
event Unstake(address indexed nameId, address indexed taoId, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId`
* @param _nameId Address to receive the tokens
* @return true on success
*/
function mintToken(address _nameId) public inWhitelist returns (bool) {
// Make sure _nameId has not received Position Token
require (receivedToken[_nameId] == false);
receivedToken[_nameId] = true;
balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME);
totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME);
emit Mint(_nameId, MAX_SUPPLY_PER_NAME);
return true;
}
/**
* @dev Get staked balance of `_nameId`
* @param _nameId The Name ID to be queried
* @return total staked balance
*/
function stakedBalance(address _nameId) public view returns (uint256) {
return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]);
}
/**
* @dev Stake `_value` tokens on `_taoId` from `_nameId`
* @param _nameId The Name ID that wants to stake
* @param _taoId The TAO ID to stake
* @param _value The amount to stake
* @return true on success
*/
function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough
balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
/**
* @dev Unstake `_value` tokens from `_nameId`'s `_taoId`
* @param _nameId The Name ID that wants to unstake
* @param _taoId The TAO ID to unstake
* @param _value The amount to unstake
* @return true on success
*/
function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough
require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value);
balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance
emit Unstake(_nameId, _taoId, _value);
return true;
}
}
/**
* @title NameTAOLookup
*
*/
contract NameTAOLookup is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
struct NameTAOInfo {
string name;
address nameTAOAddress;
string parentName;
uint256 typeId; // 0 = TAO. 1 = Name
}
uint256 public internalId;
uint256 public totalNames;
uint256 public totalTAOs;
mapping (uint256 => NameTAOInfo) internal nameTAOInfos;
mapping (bytes32 => uint256) internal internalIdLookup;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a name exist in the list
* @param _name The name to be checked
* @return true if yes, false otherwise
*/
function isExist(string _name) public view returns (bool) {
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
return (internalIdLookup[_nameKey] > 0);
}
/**
* @dev Add a new NameTAOInfo
* @param _name The name of the Name/TAO
* @param _nameTAOAddress The address of the Name/TAO
* @param _parentName The parent name of the Name/TAO
* @param _typeId If TAO = 0. Name = 1
* @return true on success
*/
function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) {
require (bytes(_name).length > 0);
require (_nameTAOAddress != address(0));
require (bytes(_parentName).length > 0);
require (_typeId == 0 || _typeId == 1);
require (!isExist(_name));
internalId++;
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
internalIdLookup[_nameKey] = internalId;
NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId];
_nameTAOInfo.name = _name;
_nameTAOInfo.nameTAOAddress = _nameTAOAddress;
_nameTAOInfo.parentName = _parentName;
_nameTAOInfo.typeId = _typeId;
if (_typeId == 0) {
totalTAOs++;
} else {
totalNames++;
}
return true;
}
/**
* @dev Get the NameTAOInfo given a name
* @param _name The name to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByName(string _name) public view returns (string, address, string, uint256) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Get the NameTAOInfo given an ID
* @param _internalId The internal ID to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) {
require (nameTAOInfos[_internalId].nameTAOAddress != address(0));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Return the nameTAOAddress given a _name
* @param _name The name to be queried
* @return the nameTAOAddress of the name
*/
function getAddressByName(string _name) public view returns (address) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return _nameTAOInfo.nameTAOAddress;
}
}
/**
* @title NamePublicKey
*/
contract NamePublicKey {
using SafeMath for uint256;
address public nameFactoryAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
struct PublicKey {
bool created;
address defaultKey;
address[] keys;
}
// Mapping from nameId to its PublicKey
mapping (address => PublicKey) internal publicKeys;
// Event to be broadcasted to public when a publicKey is added to a Name
event AddKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is removed from a Name
event RemoveKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is set as default for a Name
event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress);
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name ID exist in the list of Public Keys
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return publicKeys[_id].created;
}
/**
* @dev Store the PublicKey info for a Name
* @param _id The ID of the Name
* @param _defaultKey The default public key for this Name
* @return true on success
*/
function add(address _id, address _defaultKey)
public
isName(_id)
onlyFactory returns (bool) {
require (!isExist(_id));
require (_defaultKey != address(0));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.created = true;
_publicKey.defaultKey = _defaultKey;
_publicKey.keys.push(_defaultKey);
return true;
}
/**
* @dev Get total publicKeys count for a Name
* @param _id The ID of the Name
* @return total publicKeys count
*/
function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) {
require (isExist(_id));
return publicKeys[_id].keys.length;
}
/**
* @dev Check whether or not a publicKey exist in the list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to check
* @return true if yes. false otherwise
*/
function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) {
require (isExist(_id));
require (_key != address(0));
PublicKey memory _publicKey = publicKeys[_id];
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
return true;
}
}
return false;
}
/**
* @dev Add publicKey to list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to be added
*/
function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (!isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.keys.push(_key);
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit AddKey(_id, _key, _nonce);
}
/**
* @dev Get default public key of a Name
* @param _id The ID of the Name
* @return the default public key
*/
function getDefaultKey(address _id) public isName(_id) view returns (address) {
require (isExist(_id));
return publicKeys[_id].defaultKey;
}
/**
* @dev Get list of publicKeys of a Name
* @param _id The ID of the Name
* @param _from The starting index
* @param _to The ending index
* @return list of publicKeys
*/
function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) {
require (isExist(_id));
require (_from >= 0 && _to >= _from);
PublicKey memory _publicKey = publicKeys[_id];
require (_publicKey.keys.length > 0);
address[] memory _keys = new address[](_to.sub(_from).add(1));
if (_to > _publicKey.keys.length.sub(1)) {
_to = _publicKey.keys.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_keys[i.sub(_from)] = _publicKey.keys[i];
}
return _keys;
}
/**
* @dev Remove publicKey from the list
* @param _id The ID of the Name
* @param _key The publicKey to be removed
*/
function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
// Can't remove default key
require (_key != _publicKey.defaultKey);
require (_publicKey.keys.length > 1);
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
delete _publicKey.keys[i];
_publicKey.keys.length--;
uint256 _nonce = _nameFactory.incrementNonce(_id);
break;
}
}
require (_nonce > 0);
emit RemoveKey(_id, _key, _nonce);
}
/**
* @dev Set a publicKey as the default for a Name
* @param _id The ID of the Name
* @param _defaultKey The defaultKey to be set
* @param _signatureV The V part of the signature for this update
* @param _signatureR The R part of the signature for this update
* @param _signatureS The S part of the signature for this update
*/
function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _defaultKey));
bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));
require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.defaultKey = _defaultKey;
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit SetDefaultKey(_id, _defaultKey, _nonce);
}
}
/**
* @title NameFactory
*
* The purpose of this contract is to allow node to create Name
*/
contract NameFactory is TheAO {
using SafeMath for uint256;
address public positionAddress;
address public nameTAOVaultAddress;
address public nameTAOLookupAddress;
address public namePublicKeyAddress;
Position internal _position;
NameTAOLookup internal _nameTAOLookup;
NameTAOPosition internal _nameTAOPosition;
NamePublicKey internal _namePublicKey;
address[] internal names;
// Mapping from eth address to Name ID
mapping (address => address) public ethAddressToNameId;
// Mapping from Name ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when a Name is created
event CreateName(address indexed ethAddress, address nameId, uint256 index, string name);
/**
* @dev Constructor function
*/
constructor(address _positionAddress, address _nameTAOVaultAddress) public {
positionAddress = _positionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_position = Position(positionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update Name's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOLookup Address
* @param _nameTAOLookupAddress The address of NameTAOLookup
*/
function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO {
require (_nameTAOLookupAddress != address(0));
nameTAOLookupAddress = _nameTAOLookupAddress;
_nameTAOLookup = NameTAOLookup(nameTAOLookupAddress);
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = NamePublicKey(namePublicKeyAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a Name
* @param _nameId The ID of the Name
* @return current nonce
*/
function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) {
// Check if _nameId exist
require (nonces[_nameId] > 0);
nonces[_nameId]++;
return nonces[_nameId];
}
/**
* @dev Create a Name
* @param _name The name of the Name
* @param _datHash The datHash to this Name's profile
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
*/
function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
// Only one Name per ETH address
require (ethAddressToNameId[msg.sender] == address(0));
// The address is the Name ID (which is also a TAO ID)
address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[nameId]++;
ethAddressToNameId[msg.sender] = nameId;
// Store the name lookup information
require (_nameTAOLookup.add(_name, nameId, 'human', 1));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(nameId, nameId, nameId, nameId));
// Store the public key information
require (_namePublicKey.add(nameId, msg.sender));
names.push(nameId);
// Need to mint Position token for this Name
require (_position.mintToken(nameId));
emit CreateName(msg.sender, nameId, names.length.sub(1), _name);
}
/**
* @dev Get Name information
* @param _nameId The ID of the Name to be queried
* @return The name of the Name
* @return The originId of the Name (in this case, it's the creator node's ETH address)
* @return The datHash of the Name
* @return The database of the Name
* @return The keyValue of the Name
* @return The contentId of the Name
* @return The typeId of the Name
*/
function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) {
Name _name = Name(_nameId);
return (
_name.name(),
_name.originId(),
_name.datHash(),
_name.database(),
_name.keyValue(),
_name.contentId(),
_name.typeId()
);
}
/**
* @dev Get total Names count
* @return total Names count
*/
function getTotalNamesCount() public view returns (uint256) {
return names.length;
}
/**
* @dev Get list of Name IDs
* @param _from The starting index
* @param _to The ending index
* @return list of Name IDs
*/
function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from);
require (names.length > 0);
address[] memory _names = new address[](_to.sub(_from).add(1));
if (_to > names.length.sub(1)) {
_to = names.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_names[i.sub(_from)] = names[i];
}
return _names;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be Name's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The name of the Name
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
*/
function validateNameSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public view returns (bool) {
require (_nameTAOLookup.isExist(_name));
address _nameId = _nameTAOLookup.getAddressByName(_name);
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_validateAddress != address(0)) {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _validateAddress &&
_namePublicKey.isKeyExist(_nameId, _validateAddress)
);
} else {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _namePublicKey.getDefaultKey(_nameId)
);
}
}
}
/**
* @title AOStringSetting
*
* This contract stores all AO string setting variables
*/
contract AOStringSetting is TheAO {
// Mapping from settingId to it's actual string value
mapping (uint256 => string) public settingValue;
// Mapping from settingId to it's potential string value that is at pending state
mapping (uint256 => string) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The string value to be set
*/
function setPendingValue(uint256 _settingId, string _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
string memory _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBytesSetting
*
* This contract stores all AO bytes32 setting variables
*/
contract AOBytesSetting is TheAO {
// Mapping from settingId to it's actual bytes32 value
mapping (uint256 => bytes32) public settingValue;
// Mapping from settingId to it's potential bytes32 value that is at pending state
mapping (uint256 => bytes32) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bytes32 value to be set
*/
function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bytes32 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOAddressSetting
*
* This contract stores all AO address setting variables
*/
contract AOAddressSetting is TheAO {
// Mapping from settingId to it's actual address value
mapping (uint256 => address) public settingValue;
// Mapping from settingId to it's potential address value that is at pending state
mapping (uint256 => address) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The address value to be set
*/
function setPendingValue(uint256 _settingId, address _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
address _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBoolSetting
*
* This contract stores all AO bool setting variables
*/
contract AOBoolSetting is TheAO {
// Mapping from settingId to it's actual bool value
mapping (uint256 => bool) public settingValue;
// Mapping from settingId to it's potential bool value that is at pending state
mapping (uint256 => bool) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bool value to be set
*/
function setPendingValue(uint256 _settingId, bool _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bool _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOUintSetting
*
* This contract stores all AO uint256 setting variables
*/
contract AOUintSetting is TheAO {
// Mapping from settingId to it's actual uint256 value
mapping (uint256 => uint256) public settingValue;
// Mapping from settingId to it's potential uint256 value that is at pending state
mapping (uint256 => uint256) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The uint256 value to be set
*/
function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
uint256 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOSettingAttribute
*
* This contract stores all AO setting data/state
*/
contract AOSettingAttribute is TheAO {
NameTAOPosition internal _nameTAOPosition;
struct SettingData {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created the setting
address creatorTAOId; // The taoId that created the setting
address associatedTAOId; // The taoId that the setting affects
string settingName; // The human-readable name of the setting
/**
* 1 => uint256
* 2 => bool
* 3 => address
* 4 => bytes32
* 5 => string (catch all)
*/
uint8 settingType;
bool pendingCreate; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
string settingDataJSON; // Catch-all
}
struct SettingState {
uint256 settingId; // Identifier of this setting
bool pendingUpdate; // State when setting is in process of being updated
address updateAdvocateNameId; // The nameId of the Advocate that performed the update
/**
* A child of the associatedTAOId with the update Logos.
* This tells the setting contract that there is a proposal TAO that is a Child TAO
* of the associated TAO, which will be responsible for deciding if the update to the
* setting is accepted or rejected.
*/
address proposalTAOId;
/**
* Signature of the proposalTAOId and update value by the associatedTAOId
* Advocate's Name's address.
*/
string updateSignature;
/**
* The proposalTAOId moves here when setting value changes successfully
*/
address lastUpdateTAOId;
string settingStateJSON; // Catch-all
}
struct SettingDeprecation {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created this deprecation
address creatorTAOId; // The taoId that created this deprecation
address associatedTAOId; // The taoId that the setting affects
bool pendingDeprecated; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
bool migrated; // State when this setting is fully migrated
// holds the pending new settingId value when a deprecation is set
uint256 pendingNewSettingId;
// holds the new settingId that has been approved by associatedTAOId
uint256 newSettingId;
// holds the pending new contract address for this setting
address pendingNewSettingContractAddress;
// holds the new contract address for this setting
address newSettingContractAddress;
}
struct AssociatedTAOSetting {
bytes32 associatedTAOSettingId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSetting {
bytes32 creatorTAOSettingId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
struct AssociatedTAOSettingDeprecation {
bytes32 associatedTAOSettingDeprecationId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSettingDeprecation {
bytes32 creatorTAOSettingDeprecationId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
// Mapping from settingId to it's data
mapping (uint256 => SettingData) internal settingDatas;
// Mapping from settingId to it's state
mapping (uint256 => SettingState) internal settingStates;
// Mapping from settingId to it's deprecation info
mapping (uint256 => SettingDeprecation) internal settingDeprecations;
// Mapping from associatedTAOSettingId to AssociatedTAOSetting
mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings;
// Mapping from creatorTAOSettingId to CreatorTAOSetting
mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings;
// Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation
mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations;
// Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation
mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations;
/**
* @dev Constructor function
*/
constructor(address _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Add setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return The ID of the "Associated" setting
* @return The ID of the "Creator" setting
*/
function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) {
// Store setting data/state
require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData));
// Store the associatedTAOSetting info
bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
_associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId;
_associatedTAOSetting.associatedTAOId = _associatedTAOId;
_associatedTAOSetting.settingId = _settingId;
// Store the creatorTAOSetting info
bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
_creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId;
_creatorTAOSetting.creatorTAOId = _creatorTAOId;
_creatorTAOSetting.settingId = _settingId;
return (_associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Get Setting Data of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) {
SettingData memory _settingData = settingDatas[_settingId];
return (
_settingData.settingId,
_settingData.creatorNameId,
_settingData.creatorTAOId,
_settingData.associatedTAOId,
_settingData.settingName,
_settingData.settingType,
_settingData.pendingCreate,
_settingData.locked,
_settingData.rejected,
_settingData.settingDataJSON
);
}
/**
* @dev Get Associated TAO Setting info
* @param _associatedTAOSettingId The ID of the associated tao setting
*/
function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) {
AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
return (
_associatedTAOSetting.associatedTAOSettingId,
_associatedTAOSetting.associatedTAOId,
_associatedTAOSetting.settingId
);
}
/**
* @dev Get Creator TAO Setting info
* @param _creatorTAOSettingId The ID of the creator tao setting
*/
function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) {
CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
return (
_creatorTAOSetting.creatorTAOSettingId,
_creatorTAOSetting.creatorTAOId,
_creatorTAOSetting.settingId
);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingData.locked = false;
} else {
// Reject the setting
_settingData.pendingCreate = false;
_settingData.rejected = true;
}
return true;
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == false &&
_settingData.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId)
);
// Update the setting data
_settingData.pendingCreate = false;
_settingData.locked = true;
return true;
}
/**
* @dev Store setting update data
* @param _settingId The ID of the setting to be updated
* @param _settingType The type of this setting
* @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData memory _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.settingType == _settingType &&
_settingData.pendingCreate == false &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) &&
bytes(_updateSignature).length > 0
);
// Make sure setting is not in the middle of updating
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.pendingUpdate == false);
// Make sure setting is not yet deprecated
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
if (_settingDeprecation.settingId == _settingId) {
require (_settingDeprecation.migrated == false);
}
// Store the SettingState data
_settingState.pendingUpdate = true;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
_settingState.proposalTAOId = _proposalTAOId;
_settingState.updateSignature = _updateSignature;
_settingState.settingStateJSON = _extraData;
return true;
}
/**
* @dev Get setting state
* @param _settingId The ID of the setting
*/
function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) {
SettingState memory _settingState = settingStates[_settingId];
return (
_settingState.settingId,
_settingState.pendingUpdate,
_settingState.updateAdvocateNameId,
_settingState.proposalTAOId,
_settingState.updateSignature,
_settingState.lastUpdateTAOId,
_settingState.settingStateJSON
);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _proposalTAOAdvocate The advocate of the proposal TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId &&
_settingState.pendingUpdate == true &&
_proposalTAOAdvocate != address(0) &&
_proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of associatedTAOId can finalize the update
_settingData.locked = false;
} else {
// Set pendingUpdate to false
_settingState.pendingUpdate = false;
_settingState.proposalTAOId = address(0);
}
return true;
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @return true on success
*/
function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == false &&
_settingData.locked == false &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0));
// Update the setting data
_settingData.locked = true;
// Update the setting state
_settingState.pendingUpdate = false;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
address _proposalTAOId = _settingState.proposalTAOId;
_settingState.proposalTAOId = address(0);
_settingState.lastUpdateTAOId = _proposalTAOId;
return true;
}
/**
* @dev Add setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return The ID of the "Associated" setting deprecation
* @return The ID of the "Creator" setting deprecation
*/
function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) {
require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress));
// Store the associatedTAOSettingDeprecation info
bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId;
_associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId;
_associatedTAOSettingDeprecation.settingId = _settingId;
// Store the creatorTAOSettingDeprecation info
bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId;
_creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId;
_creatorTAOSettingDeprecation.settingId = _settingId;
return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Get Setting Deprecation info of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) {
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
return (
_settingDeprecation.settingId,
_settingDeprecation.creatorNameId,
_settingDeprecation.creatorTAOId,
_settingDeprecation.associatedTAOId,
_settingDeprecation.pendingDeprecated,
_settingDeprecation.locked,
_settingDeprecation.rejected,
_settingDeprecation.migrated,
_settingDeprecation.pendingNewSettingId,
_settingDeprecation.newSettingId,
_settingDeprecation.pendingNewSettingContractAddress,
_settingDeprecation.newSettingContractAddress
);
}
/**
* @dev Get Associated TAO Setting Deprecation info
* @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation
*/
function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
return (
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId,
_associatedTAOSettingDeprecation.associatedTAOId,
_associatedTAOSettingDeprecation.settingId
);
}
/**
* @dev Get Creator TAO Setting Deprecation info
* @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation
*/
function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
return (
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId,
_creatorTAOSettingDeprecation.creatorTAOId,
_creatorTAOSettingDeprecation.settingId
);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == true &&
_settingDeprecation.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingDeprecation.locked = false;
} else {
// Reject the setting
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.rejected = true;
}
return true;
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == false &&
_settingDeprecation.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId)
);
// Update the setting data
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.locked = true;
_settingDeprecation.migrated = true;
uint256 _newSettingId = _settingDeprecation.pendingNewSettingId;
_settingDeprecation.pendingNewSettingId = 0;
_settingDeprecation.newSettingId = _newSettingId;
address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress;
_settingDeprecation.pendingNewSettingContractAddress = address(0);
_settingDeprecation.newSettingContractAddress = _newSettingContractAddress;
return true;
}
/**
* @dev Check if a setting exist and not rejected
* @param _settingId The ID of the setting
* @return true if exist. false otherwise
*/
function settingExist(uint256 _settingId) public view returns (bool) {
SettingData memory _settingData = settingDatas[_settingId];
return (_settingData.settingId == _settingId && _settingData.rejected == false);
}
/**
* @dev Get the latest ID of a deprecated setting, if exist
* @param _settingId The ID of the setting
* @return The latest setting ID
*/
function getLatestSettingId(uint256 _settingId) public view returns (uint256) {
(,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId);
while (_migrated && _newSettingId > 0) {
_settingId = _newSettingId;
(,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId);
}
return _settingId;
}
/***** Internal Method *****/
/**
* @dev Store setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) {
// Store setting data
SettingData storage _settingData = settingDatas[_settingId];
_settingData.settingId = _settingId;
_settingData.creatorNameId = _creatorNameId;
_settingData.creatorTAOId = _creatorTAOId;
_settingData.associatedTAOId = _associatedTAOId;
_settingData.settingName = _settingName;
_settingData.settingType = _settingType;
_settingData.pendingCreate = true;
_settingData.locked = true;
_settingData.settingDataJSON = _extraData;
// Store setting state
SettingState storage _settingState = settingStates[_settingId];
_settingState.settingId = _settingId;
return true;
}
/**
* @dev Store setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return true on success
*/
function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) {
// Make sure this setting exists
require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false);
// Make sure deprecation is not yet exist for this setting Id
require (settingDeprecations[_settingId].creatorNameId == address(0));
// Make sure newSettingId exists
require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false);
// Make sure the settingType matches
require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType);
// Store setting deprecation info
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
_settingDeprecation.settingId = _settingId;
_settingDeprecation.creatorNameId = _creatorNameId;
_settingDeprecation.creatorTAOId = _creatorTAOId;
_settingDeprecation.associatedTAOId = _associatedTAOId;
_settingDeprecation.pendingDeprecated = true;
_settingDeprecation.locked = true;
_settingDeprecation.pendingNewSettingId = _newSettingId;
_settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress;
return true;
}
}
/**
* @title AOTokenInterface
*/
contract AOTokenInterface is TheAO, TokenERC20 {
using SafeMath for uint256;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK TOKEN VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Prevent/Allow target from sending & receiving tokens
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target` escrow balance
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive in escrow
*/
function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(this, target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network tokens to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Buy tokens from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `amount` tokens to contract
* @param amount The amount of tokens to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = this;
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title AOToken
*/
contract AOToken is AOTokenInterface {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
// AO Dev Team addresses to receive Primordial/Network Tokens
address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52;
address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28;
AOSetting internal _aoSetting;
/***** PRIMORDIAL TOKEN VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
// Total available primordial token for sale 1,125,899,906,842,620 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked tokens
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
uint256 public totalLots;
uint256 public totalBurnLots;
uint256 public totalConvertLots;
bool public networkExchangeEnded;
/**
* Stores Lot creation data (during network exchange)
*/
struct Lot {
bytes32 lotId;
uint256 multiplier; // This value is in 10^6, so 1000000 = 1
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account burns primordial token
*/
struct BurnLot {
bytes32 burnLotId;
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account converts network token to primordial token
*/
struct ConvertLot {
bytes32 convertLotId;
address lotOwner;
uint256 tokenAmount;
}
// Mapping from Lot ID to Lot object
mapping (bytes32 => Lot) internal lots;
// Mapping from Burn Lot ID to BurnLot object
mapping (bytes32 => BurnLot) internal burnLots;
// Mapping from Convert Lot ID to ConvertLot object
mapping (bytes32 => ConvertLot) internal convertLots;
// Mapping from owner to list of owned lot IDs
mapping (address => bytes32[]) internal ownedLots;
// Mapping from owner to list of owned burn lot IDs
mapping (address => bytes32[]) internal ownedBurnLots;
// Mapping from owner to list of owned convert lot IDs
mapping (address => bytes32[]) internal ownedConvertLots;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when a lot is created
// multiplier value is in 10^6 to account for 6 decimal points
event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount);
// Event to be broadcasted to public when burn lot is created (when account burns primordial tokens)
event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn);
// Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens)
event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress)
AOTokenInterface(initialSupply, tokenName, tokenSymbol) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
_aoSetting = AOSetting(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token
}
/**
* @dev Checks if buyer can buy primordial token
*/
modifier canBuyPrimordial(uint256 _sentAmount) {
require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial tokens to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial tokens to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/***** PUBLIC METHODS *****/
/***** Primordial TOKEN PUBLIC METHODS *****/
/**
* @dev Buy Primordial tokens from contract by sending ether
*/
function buyPrimordialToken() public payable canBuyPrimordial(msg.value) {
(uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value);
require (tokenAmount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
// Send the primordial token to buyer and reward AO devs
_sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Send `_value` Primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(msg.sender, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Send `_value` Primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordialToken(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialToken(uint256 _value) public returns (bool success) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(msg.sender, _value);
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(_from, _value);
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return all lot IDs owned by an address
* @param _lotOwner The address of the lot owner
* @return array of lot IDs
*/
function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedLots[_lotOwner];
}
/**
* @dev Return the total lots owned by an address
* @param _lotOwner The address of the lot owner
* @return total lots owner by the address
*/
function totalLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedLots[_lotOwner].length;
}
/**
* @dev Return the lot information at a given index of the lots list of the requested owner
* @param _lotOwner The address owning the lots list to be accessed
* @param _index uint256 representing the index to be accessed of the requested lots list
* @return id of the lot
* @return The address of the lot owner
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) {
require (_index < ownedLots[_lotOwner].length);
Lot memory _lot = lots[ownedLots[_lotOwner][_index]];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return the lot information at a given ID
* @param _lotId The lot ID in question
* @return id of the lot
* @return The lot owner address
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) {
Lot memory _lot = lots[_lotId];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return all Burn Lot IDs owned by an address
* @param _lotOwner The address of the burn lot owner
* @return array of Burn Lot IDs
*/
function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedBurnLots[_lotOwner];
}
/**
* @dev Return the total burn lots owned by an address
* @param _lotOwner The address of the burn lot owner
* @return total burn lots owner by the address
*/
function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedBurnLots[_lotOwner].length;
}
/**
* @dev Return the burn lot information at a given ID
* @param _burnLotId The burn lot ID in question
* @return id of the lot
* @return The address of the burn lot owner
* @return Primordial token amount in the burn lot
*/
function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) {
BurnLot memory _burnLot = burnLots[_burnLotId];
return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount);
}
/**
* @dev Return all Convert Lot IDs owned by an address
* @param _lotOwner The address of the convert lot owner
* @return array of Convert Lot IDs
*/
function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedConvertLots[_lotOwner];
}
/**
* @dev Return the total convert lots owned by an address
* @param _lotOwner The address of the convert lot owner
* @return total convert lots owner by the address
*/
function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedConvertLots[_lotOwner].length;
}
/**
* @dev Return the convert lot information at a given ID
* @param _convertLotId The convert lot ID in question
* @return id of the lot
* @return The address of the convert lot owner
* @return Primordial token amount in the convert lot
*/
function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) {
ConvertLot memory _convertLot = convertLots[_convertLotId];
return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount);
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial token multiplier, bonus network token percentage, and the
* bonus network token amount on a given lot when someone purchases primordial token
* during network exchange
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network token as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier),
AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial token amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens
* @param _account The address of the account
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token
* @param _account The address of the account
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network tokens to primordial tokens
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool success) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network token
burn(_value);
// mint primordial token
_mintPrimordialToken(msg.sender, _value);
// Store convert lot info
totalConvertLots++;
// Generate convert lot Id
bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots));
// Make sure no one owns this lot yet
require (convertLots[convertLotId].lotOwner == address(0));
ConvertLot storage convertLot = convertLots[convertLotId];
convertLot.convertLotId = convertLotId;
convertLot.lotOwner = msg.sender;
convertLot.tokenAmount = _value;
ownedConvertLots[msg.sender].push(convertLotId);
emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]);
return true;
}
/***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount of network tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transfer(_to, _value));
require (transferPrimordialToken(_to, _primordialValue));
return true;
}
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transferFrom(_from, _to, _value));
require (transferPrimordialTokenFrom(_from, _to, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of network tokens they can spend
* @return true on success
*/
function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.approve(_spender, _value));
require (approvePrimordialToken(_spender, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of Primordial Tokens they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) {
require (super.approveAndCall(_spender, _value, _extraData));
require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burn(_value));
require (burnPrimordialToken(_primordialValue));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from`
* @param _from The address of sender
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burnFrom(_from, _value));
require (burnPrimordialTokenFrom(_from, _primordialValue));
return true;
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL TOKEN INTERNAL METHODS *****/
/**
* @dev Calculate the amount of token the buyer will receive and remaining budget if exist
* when he/she buys primordial token
* @param _budget The amount of ETH sent by buyer
* @return uint256 of the tokenAmount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) {
// Calculate the amount of tokens
uint256 tokenAmount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial token to be purchased
uint256 remainderEth = 0;
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice));
}
return (tokenAmount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial token to buyer and reward AO devs accordingly
* @param tokenAmount The amount of primordial token to be sent to buyer
* @param to The recipient of the token
*/
function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount);
primordialTotalBought = primordialTotalBought.add(tokenAmount);
_createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
_mintToken(theAO, theAONetworkTokenBonusAmount);
}
/**
* @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account`
* during network exchange, and reward `_networkTokenBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkTokenBonusAmount The network token bonus amount
*/
function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal {
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _multiplier;
lot.lotOwner = _account;
lot.tokenAmount = _primordialTokenAmount;
ownedLots[_account].push(lotId);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
_mintPrimordialToken(_account, lot.tokenAmount);
_mintToken(_account, _networkTokenBonusAmount);
emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount);
}
/**
* @dev Create `mintedAmount` Primordial tokens and send it to `target`
* @param target Address to receive the Primordial tokens
* @param mintedAmount The amount of Primordial tokens it will receive
*/
function _mintPrimordialToken(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(0, this, mintedAmount);
emit PrimordialTransfer(this, target, mintedAmount);
}
/**
* @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _tokenAmount The amount of tokens
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_tokenAmount > 0);
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _weightedMultiplier;
lot.lotOwner = _account;
lot.tokenAmount = _tokenAmount;
ownedLots[_account].push(lotId);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
return lotId;
}
/**
* @dev Send `_value` Primordial tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Store burn lot information
* @param _account The address of the account
* @param _tokenAmount The amount of primordial tokens to burn
*/
function _createBurnLot(address _account, uint256 _tokenAmount) internal {
totalBurnLots++;
// Generate burn lot Id
bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots));
// Make sure no one owns this lot yet
require (burnLots[burnLotId].lotOwner == address(0));
BurnLot storage burnLot = burnLots[burnLotId];
burnLot.burnLotId = burnLotId;
burnLot.lotOwner = _account;
burnLot.tokenAmount = _tokenAmount;
ownedBurnLots[_account].push(burnLotId);
emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]);
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token
* @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus
* @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier');
(uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier);
}
}
/**
* @title AOTreasury
*
* The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations
*/
contract AOTreasury is TheAO {
using SafeMath for uint256;
bool public paused;
bool public killed;
struct Denomination {
bytes8 name;
address denominationAddress;
}
// Mapping from denomination index to Denomination object
// The list is in order from lowest denomination to highest denomination
// i.e, denominations[1] is the base denomination
mapping (uint256 => Denomination) internal denominations;
// Mapping from denomination ID to index of denominations
mapping (bytes8 => uint256) internal denominationIndex;
uint256 public totalDenominations;
// Event to be broadcasted to public when a token exchange happens
event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/**
* @dev Checks if denomination is valid
*/
modifier isValidDenomination(bytes8 denominationName) {
require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO adds denomination and the contract address associated with it
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationAddress != address(0));
require (denominationIndex[denominationName] == 0);
totalDenominations++;
// Make sure the new denomination is higher than the previous
if (totalDenominations > 1) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress);
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen());
}
denominations[totalDenominations].name = denominationName;
denominations[totalDenominations].denominationAddress = denominationAddress;
denominationIndex[denominationName] = totalDenominations;
return true;
}
/**
* @dev The AO updates denomination address or activates/deactivates the denomination
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominationAddress != address(0));
uint256 _denominationNameIndex = denominationIndex[denominationName];
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
if (_denominationNameIndex > 1) {
AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress);
require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen());
}
if (_denominationNameIndex < totalDenominations) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress);
require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen());
}
denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get denomination info based on name
* @param denominationName The name to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominations[denominationIndex[denominationName]].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress);
return (
denominations[denominationIndex[denominationName]].name,
denominations[denominationIndex[denominationName]].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get denomination info by index
* @param index The index to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) {
require (index > 0 && index <= totalDenominations);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get base denomination info
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) {
require (totalDenominations > 1);
return getDenominationByIndex(1);
}
/**
* @dev convert token from `denominationName` denomination to base denomination,
* in this case it's similar to web3.toWei() functionality
*
* Example:
* 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount
* 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount
* 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount
*
* @param integerAmount uint256 of the integer amount to be converted
* @param fractionAmount uint256 of the frational amount to be converted
* @param denominationName bytes8 name of the token denomination
* @return uint256 converted amount in base denomination from target denomination
*/
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) {
if (denominationName.length > 0 &&
denominationIndex[denominationName] > 0 &&
denominations[denominationIndex[denominationName]].denominationAddress != address(0) &&
(integerAmount > 0 || fractionAmount > 0)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint8 fractionNumDigits = _numDigits(fractionAmount);
require (fractionNumDigits <= _denominationToken.decimals());
uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen());
if (_denominationToken.decimals() == 0) {
fractionAmount = 0;
}
return baseInteger.add(fractionAmount);
} else {
return 0;
}
}
/**
* @dev convert token from base denomination to `denominationName` denomination,
* in this case it's similar to web3.fromWei() functionality
* @param integerAmount uint256 of the base amount to be converted
* @param denominationName bytes8 name of the target token denomination
* @return uint256 of the converted integer amount in target denomination
* @return uint256 of the converted fraction amount in target denomination
*/
function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen());
uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen()));
return (denominationInteger, denominationFraction);
}
/**
* @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination
* @param amount The amount of token to exchange
* @param fromDenominationName The origin denomination
* @param toDenominationName The target denomination
*/
function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {
require (amount > 0);
Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];
Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];
AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress);
AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress);
require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount));
require (_toDenominationToken.mintToken(msg.sender, amount));
emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName);
}
/**
* @dev Return the highest possible denomination given a base amount
* @param amount The amount to be converted
* @return the denomination short name
* @return the denomination address
* @return the integer amount at the denomination level
* @return the fraction amount at the denomination level
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) {
uint256 integerAmount;
uint256 fractionAmount;
uint256 index;
for (uint256 i=totalDenominations; i>0; i--) {
Denomination memory _denomination = denominations[i];
(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);
if (integerAmount > 0) {
index = i;
break;
}
}
require (index > 0 && index <= totalDenominations);
require (integerAmount > 0 || fractionAmount > 0);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
integerAmount,
fractionAmount,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/***** INTERNAL METHOD *****/
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function _numDigits(uint256 number) internal pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
contract Pathos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
contract Ethos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
/**
* @title TAOController
*/
contract TAOController {
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of TAO ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
}
// Store the name lookup for a Name/TAO
/**
* @title TAOFamily
*/
contract TAOFamily is TAOController {
using SafeMath for uint256;
address public taoFactoryAddress;
TAOFactory internal _taoFactory;
struct Child {
address taoId;
bool approved; // If false, then waiting for parent TAO approval
bool connected; // If false, then parent TAO want to remove this child TAO
}
struct Family {
address taoId;
address parentId; // The parent of this TAO ID (could be a Name or TAO)
uint256 childMinLogos;
mapping (uint256 => Child) children;
mapping (address => uint256) childInternalIdLookup;
uint256 totalChildren;
uint256 childInternalId;
}
mapping (address => Family) internal families;
// Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO
event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce);
// Event to be broadcasted to public when a TAO adds a child TAO
event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce);
// Event to be broadcasted to public when a TAO approves a child TAO
event ApproveChild(address indexed taoId, address childId, uint256 nonce);
// Event to be broadcasted to public when a TAO removes a child TAO
event RemoveChild(address indexed taoId, address childId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a TAO ID exist in the list of families
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return families[_id].taoId != address(0);
}
/**
* @dev Store the Family info for a TAO
* @param _id The ID of the TAO
* @param _parentId The parent ID of this TAO
* @param _childMinLogos The min required Logos to create a TAO
* @return true on success
*/
function add(address _id, address _parentId, uint256 _childMinLogos)
public
isTAO(_id)
isNameOrTAO(_parentId)
onlyFactory returns (bool) {
require (!isExist(_id));
Family storage _family = families[_id];
_family.taoId = _id;
_family.parentId = _parentId;
_family.childMinLogos = _childMinLogos;
return true;
}
/**
* @dev Get Family info given a TAO ID
* @param _id The ID of the TAO
* @return the parent ID of this TAO (could be a Name/TAO)
* @return the min required Logos to create a child TAO
* @return the total child TAOs count
*/
function getFamilyById(address _id) public view returns (address, uint256, uint256) {
require (isExist(_id));
Family memory _family = families[_id];
return (
_family.parentId,
_family.childMinLogos,
_family.totalChildren
);
}
/**
* @dev Set min required Logos to create a child from this TAO
* @param _childMinLogos The min Logos to set
* @return the nonce for this transaction
*/
function updateChildMinLogos(address _id, uint256 _childMinLogos)
public
isTAO(_id)
senderIsName()
onlyAdvocate(_id) {
require (isExist(_id));
Family storage _family = families[_id];
_family.childMinLogos = _childMinLogos;
uint256 _nonce = _taoFactory.incrementNonce(_id);
require (_nonce > 0);
emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isChild(address _taoId, address _childId) public view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family memory _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
_family.children[_childInternalId].approved &&
_family.children[_childInternalId].connected &&
_childFamily.parentId == _taoId
);
}
/**
* @dev Add child TAO
* @param _taoId The TAO ID to be added to
* @param _childId The ID to be added to as child TAO
*/
function addChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
onlyFactory returns (bool) {
require (!isChild(_taoId, _childId));
Family storage _family = families[_taoId];
require (_family.childInternalIdLookup[_childId] == 0);
_family.childInternalId++;
_family.childInternalIdLookup[_childId] = _family.childInternalId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
Child storage _child = _family.children[_family.childInternalId];
_child.taoId = _childId;
// If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected
// Otherwise, child TAO needs parent TAO approval
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
if (_taoAdvocate == _childAdvocate) {
_family.totalChildren++;
_child.approved = true;
_child.connected = true;
Family storage _childFamily = families[_childId];
_childFamily.parentId = _taoId;
}
emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce);
return true;
}
/**
* @dev Advocate of `_taoId` approves child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function approveChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family storage _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
require (_childInternalId > 0 &&
!_family.children[_childInternalId].approved &&
!_family.children[_childInternalId].connected
);
_family.totalChildren++;
Child storage _child = _family.children[_childInternalId];
_child.approved = true;
_child.connected = true;
_childFamily.parentId = _taoId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit ApproveChild(_taoId, _childId, _nonce);
}
/**
* @dev Advocate of `_taoId` removes child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be removed
*/
function removeChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isChild(_taoId, _childId));
Family storage _family = families[_taoId];
_family.totalChildren--;
Child storage _child = _family.children[_family.childInternalIdLookup[_childId]];
_child.connected = false;
_family.childInternalIdLookup[_childId] = 0;
Family storage _childFamily = families[_childId];
_childFamily.parentId = address(0);
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit RemoveChild(_taoId, _childId, _nonce);
}
/**
* @dev Get list of child TAO IDs
* @param _taoId The TAO ID to be checked
* @param _from The starting index (start from 1)
* @param _to The ending index, (max is childInternalId)
* @return list of child TAO IDs
*/
function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) {
require (isExist(_taoId));
Family storage _family = families[_taoId];
require (_from >= 1 && _to >= _from && _family.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0);
}
return _childIds;
}
}
// Store TAO's child information
/**
* @title TAOFactory
*
* The purpose of this contract is to allow node to create TAO
*/
contract TAOFactory is TheAO, TAOController {
using SafeMath for uint256;
address[] internal taos;
address public taoFamilyAddress;
address public nameTAOVaultAddress;
address public settingTAOId;
NameTAOLookup internal _nameTAOLookup;
TAOFamily internal _taoFamily;
AOSetting internal _aoSetting;
Logos internal _logos;
// Mapping from TAO ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when Advocate creates a TAO
event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_logos = Logos(_logosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update TAO's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the TAOFamily Address
* @param _taoFamilyAddress The address of TAOFamily
*/
function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO {
require (_taoFamilyAddress != address(0));
taoFamilyAddress = _taoFamilyAddress;
_taoFamily = TAOFamily(taoFamilyAddress);
}
/**
* @dev The AO set settingTAOId (The TAO ID that holds the setting values)
* @param _settingTAOId The address of settingTAOId
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) {
settingTAOId = _settingTAOId;
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a TAO
* @param _taoId The ID of the TAO
* @return current nonce
*/
function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) {
// Check if _taoId exist
require (nonces[_taoId] > 0);
nonces[_taoId]++;
return nonces[_taoId];
}
/**
* @dev Name creates a TAO
* @param _name The name of the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
*/
function createTAO(
string _name,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos
) public senderIsName() isNameOrTAO(_parentId) {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
uint256 _parentCreateChildTAOMinLogos;
uint256 _createChildTAOMinLogos = _getSettingVariables();
if (AOLibrary.isTAO(_parentId)) {
(, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId);
}
if (_parentCreateChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos);
} else if (_createChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos);
}
// Create the TAO
address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[taoId]++;
// Store the name lookup information
require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId));
require (_taoFamily.add(taoId, _parentId, _childMinLogos));
taos.push(taoId);
emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId());
if (AOLibrary.isTAO(_parentId)) {
require (_taoFamily.addChild(_parentId, taoId));
}
}
/**
* @dev Get TAO information
* @param _taoId The ID of the TAO to be queried
* @return The name of the TAO
* @return The origin Name ID that created the TAO
* @return The name of Name that created the TAO
* @return The datHash of the TAO
* @return The database of the TAO
* @return The keyValue of the TAO
* @return The contentId of the TAO
* @return The typeId of the TAO
*/
function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) {
TAO _tao = TAO(_taoId);
return (
_tao.name(),
_tao.originId(),
Name(_tao.originId()).name(),
_tao.datHash(),
_tao.database(),
_tao.keyValue(),
_tao.contentId(),
_tao.typeId()
);
}
/**
* @dev Get total TAOs count
* @return total TAOs count
*/
function getTotalTAOsCount() public view returns (uint256) {
return taos.length;
}
/**
* @dev Get list of TAO IDs
* @param _from The starting index
* @param _to The ending index
* @return list of TAO IDs
*/
function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from && taos.length > _to);
address[] memory _taos = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_taos[i.sub(_from)] = taos[i];
}
return _taos;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The Name of the TAO
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
* @return The name of the Name that created the signature
* @return The Position of the Name that created the signature.
* 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker
*/
function validateTAOSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) {
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) {
return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name)));
} else {
return (false, "", 0);
}
}
/***** INTERNAL METHOD *****/
/**
* @dev Check whether or not the address recovered from the signature is valid
* @param _validateAddress The ETH address to be validated (optional)
* @param _signatureAddress The address recovered from the signature
* @param _taoId The ID of the TAO
* @param _nonce The signed uint256 nonce
* @return true if valid. false otherwise
*/
function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
} else {
return (
_nonce == nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
/**
* @dev Internal function to get the TAO Id by name
* @param _name The name of the TAO
* @return the TAO ID
*/
function _getTAOIdByName(string _name) internal view returns (address) {
return _nameTAOLookup.getAddressByName(_name);
}
/**
* @dev Get setting variables
* @return createChildTAOMinLogos The minimum required Logos to create a TAO
*/
function _getSettingVariables() internal view returns (uint256) {
(uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos');
return createChildTAOMinLogos;
}
}
/**
* @title NameTAOPosition
*/
contract NameTAOPosition is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
NameFactory internal _nameFactory;
TAOFactory internal _taoFactory;
struct Position {
address advocateId;
address listenerId;
address speakerId;
bool created;
}
mapping (address => Position) internal positions;
// Event to be broadcasted to public when current Advocate of TAO sets New Advocate
event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener
event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker
event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
nameTAOPositionAddress = address(this);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of a Name/TAO ID
*/
modifier onlyAdvocate(address _id) {
require (senderIsAdvocate(msg.sender, _id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name/TAO ID exist in the list
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return positions[_id].created;
}
/**
* @dev Check whether or not eth address is advocate of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsAdvocate(address _sender, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender));
}
/**
* @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsPosition(address _sender, address _id) public view returns (bool) {
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == address(0)) {
return false;
} else {
return (positions[_id].created &&
(positions[_id].advocateId == _nameId ||
positions[_id].listenerId == _nameId ||
positions[_id].speakerId == _nameId
)
);
}
}
/**
* @dev Check whether or not _nameId is advocate of _id
* @param _nameId The name ID to be checked
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function nameIsAdvocate(address _nameId, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameId);
}
/**
* @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO
* @param _sender The ETH address that to check
* @param _id The ID of the Name/TAO
* @return 1 if Advocate. 2 if Listener. 3 if Speaker
*/
function determinePosition(address _sender, address _id) public view returns (uint256) {
require (senderIsPosition(_sender, _id));
Position memory _position = positions[_id];
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == _position.advocateId) {
return 1;
} else if (_nameId == _position.listenerId) {
return 2;
} else {
return 3;
}
}
/**
* @dev Add Position for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _advocateId The Advocate ID of the Name/TAO
* @param _listenerId The Listener ID of the Name/TAO
* @param _speakerId The Speaker ID of the Name/TAO
* @return true on success
*/
function add(address _id, address _advocateId, address _listenerId, address _speakerId)
public
isNameOrTAO(_id)
isName(_advocateId)
isNameOrTAO(_listenerId)
isNameOrTAO(_speakerId)
onlyFactory returns (bool) {
require (!isExist(_id));
Position storage _position = positions[_id];
_position.advocateId = _advocateId;
_position.listenerId = _listenerId;
_position.speakerId = _speakerId;
_position.created = true;
return true;
}
/**
* @dev Get Name/TAO's Position info
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
* @return the Listener ID of Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getPositionById(address _id) public view returns (address, address, address) {
require (isExist(_id));
Position memory _position = positions[_id];
return (
_position.advocateId,
_position.listenerId,
_position.speakerId
);
}
/**
* @dev Get Name/TAO's Advocate
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
*/
function getAdvocate(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.advocateId;
}
/**
* @dev Get Name/TAO's Listener
* @param _id The ID of the Name/TAO
* @return the Listener ID of Name/TAO
*/
function getListener(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.listenerId;
}
/**
* @dev Get Name/TAO's Speaker
* @param _id The ID of the Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getSpeaker(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.speakerId;
}
/**
* @dev Set Advocate for a TAO
* @param _taoId The ID of the TAO
* @param _newAdvocateId The new advocate ID to be set
*/
function setAdvocate(address _taoId, address _newAdvocateId)
public
isTAO(_taoId)
isName(_newAdvocateId)
senderIsName()
onlyAdvocate(_taoId) {
Position storage _position = positions[_taoId];
address _currentAdvocateId = _position.advocateId;
_position.advocateId = _newAdvocateId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce);
}
/**
* @dev Set Listener for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newListenerId The new listener ID to be set
*/
function setListener(address _id, address _newListenerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newListenerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Listener can only be a Name
// If _id is a TAO, then new Listener can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newListenerId));
}
Position storage _position = positions[_id];
address _currentListenerId = _position.listenerId;
_position.listenerId = _newListenerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce);
}
/**
* @dev Set Speaker for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newSpeakerId The new speaker ID to be set
*/
function setSpeaker(address _id, address _newSpeakerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newSpeakerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Speaker can only be a Name
// If _id is a TAO, then new Speaker can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newSpeakerId));
}
Position storage _position = positions[_id];
address _currentSpeakerId = _position.speakerId;
_position.speakerId = _newSpeakerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce);
}
}
/**
* @title AOSetting
*
* This contract stores all AO setting variables
*/
contract AOSetting {
address public aoSettingAttributeAddress;
address public aoUintSettingAddress;
address public aoBoolSettingAddress;
address public aoAddressSettingAddress;
address public aoBytesSettingAddress;
address public aoStringSettingAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
AOSettingAttribute internal _aoSettingAttribute;
AOUintSetting internal _aoUintSetting;
AOBoolSetting internal _aoBoolSetting;
AOAddressSetting internal _aoAddressSetting;
AOBytesSetting internal _aoBytesSetting;
AOStringSetting internal _aoStringSetting;
uint256 public totalSetting;
/**
* Mapping from associatedTAOId's setting name to Setting ID.
*
* Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup,
* use nested mapping to achieve the same result.
*
* The setting's name needs to be converted to bytes32 since solidity does not support mapping by string.
*/
mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup;
// Mapping from updateHashKey to it's settingId
mapping (bytes32 => uint256) public updateHashLookup;
// Event to be broadcasted to public when a setting is created and waiting for approval
event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId);
// Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId
event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
// Event to be broadcasted to public when a proposed update for a setting is created
event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId);
// Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId
event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId
event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate);
// Event to be broadcasted to public when a setting deprecation is created and waiting for approval
event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId);
// Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId
event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress,
address _nameTAOPositionAddress,
address _aoSettingAttributeAddress,
address _aoUintSettingAddress,
address _aoBoolSettingAddress,
address _aoAddressSettingAddress,
address _aoBytesSettingAddress,
address _aoStringSettingAddress) public {
aoSettingAttributeAddress = _aoSettingAttributeAddress;
aoUintSettingAddress = _aoUintSettingAddress;
aoBoolSettingAddress = _aoBoolSettingAddress;
aoAddressSettingAddress = _aoAddressSettingAddress;
aoBytesSettingAddress = _aoBytesSettingAddress;
aoStringSettingAddress = _aoStringSettingAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress);
_aoUintSetting = AOUintSetting(_aoUintSettingAddress);
_aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress);
_aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress);
_aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress);
_aoStringSetting = AOStringSetting(_aoStringSettingAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_settingName` of `_associatedTAOId` is taken
*/
modifier settingNameNotTaken(string _settingName, address _associatedTAOId) {
require (settingNameExist(_settingName, _associatedTAOId) == false);
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** Public Methods *****/
/**
* @dev Check whether or not a setting name of an associatedTAOId exist
* @param _settingName The human-readable name of the setting
* @param _associatedTAOId The taoId that the setting affects
* @return true if yes. false otherwise
*/
function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) {
return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0);
}
/**
* @dev Advocate of _creatorTAOId adds a uint setting
* @param _settingName The human-readable name of the setting
* @param _value The uint256 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoUintSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bool setting
* @param _settingName The human-readable name of the setting
* @param _value The bool value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBoolSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds an address setting
* @param _settingName The human-readable name of the setting
* @param _value The address value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoAddressSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bytes32 setting
* @param _settingName The human-readable name of the setting
* @param _value The bytes32 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBytesSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a string setting
* @param _settingName The human-readable name of the setting
* @param _value The string value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoStringSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingCreation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved));
(,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId);
if (!_approved) {
// Clear the settingName from nameSettingLookup so it can be added again in the future
delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingCreation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate));
(,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new uint256 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoUintSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bool value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBoolSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new address value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoAddressSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bytes32 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBytesSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new string value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoStringSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _approved Whether to approve or reject
*/
function approveSettingUpdate(uint256 _settingId, bool _approved) public {
address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
(,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId);
require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved));
emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingUpdate(uint256 _settingId) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate));
(,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate);
}
/**
* @dev Advocate of _creatorTAOId adds a setting deprecation
* @param _settingId The ID of the setting to be deprecated
* @param _newSettingId The new setting ID to route
* @param _newSettingContractAddress The new setting contract address to route
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
*/
function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) {
(bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress);
emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingDeprecation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved));
(,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingDeprecation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate));
(,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Get setting Id given an associatedTAOId and settingName
* @param _associatedTAOId The ID of the AssociatedTAO
* @param _settingName The name of the setting
* @return the ID of the setting
*/
function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) {
return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
/**
* @dev Get setting values by setting ID.
* Will throw error if the setting is not exist or rejected.
* @param _settingId The ID of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) {
require (_aoSettingAttribute.settingExist(_settingId));
_settingId = _aoSettingAttribute.getLatestSettingId(_settingId);
return (
_aoUintSetting.settingValue(_settingId),
_aoBoolSetting.settingValue(_settingId),
_aoAddressSetting.settingValue(_settingId),
_aoBytesSetting.settingValue(_settingId),
_aoStringSetting.settingValue(_settingId)
);
}
/**
* @dev Get setting values by taoId and settingName.
* Will throw error if the setting is not exist or rejected.
* @param _taoId The ID of the TAO
* @param _settingName The name of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) {
return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName));
}
/***** Internal Method *****/
/**
* @dev Store setting creation data
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal {
// Make sure _settingType is in supported list
require (_settingType >= 1 && _settingType <= 5);
// Store nameSettingLookup
nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting;
// Store setting data/state
(bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Move value of _settingId from pending variable to setting variable
* @param _settingId The ID of the setting
* @param _settingType The type of the setting
*/
function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal {
// If settingType == uint256
if (_settingType == 1) {
_aoUintSetting.movePendingToSetting(_settingId);
} else if (_settingType == 2) {
// Else if settingType == bool
_aoBoolSetting.movePendingToSetting(_settingId);
} else if (_settingType == 3) {
// Else if settingType == address
_aoAddressSetting.movePendingToSetting(_settingId);
} else if (_settingType == 4) {
// Else if settingType == bytes32
_aoBytesSetting.movePendingToSetting(_settingId);
} else {
// Else if settingType == string
_aoStringSetting.movePendingToSetting(_settingId);
}
}
}
/**
* @title AOEarning
*
* This contract stores the earning from staking/hosting content on AO
*/
contract AOEarning is TheAO {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
address public baseDenominationAddress;
address public treasuryAddress;
address public nameFactoryAddress;
address public pathosAddress;
address public ethosAddress;
bool public paused;
bool public killed;
AOToken internal _baseAO;
AOTreasury internal _treasury;
NameFactory internal _nameFactory;
Pathos internal _pathos;
Ethos internal _ethos;
AOSetting internal _aoSetting;
// Total earning from staking content from all nodes
uint256 public totalStakeContentEarning;
// Total earning from hosting content from all nodes
uint256 public totalHostContentEarning;
// Total The AO earning
uint256 public totalTheAOEarning;
// Mapping from address to his/her earning from content that he/she staked
mapping (address => uint256) public stakeContentEarning;
// Mapping from address to his/her earning from content that he/she hosted
mapping (address => uint256) public hostContentEarning;
// Mapping from address to his/her network price earning
// i.e, when staked amount = filesize
mapping (address => uint256) public networkPriceEarning;
// Mapping from address to his/her content price earning
// i.e, when staked amount > filesize
mapping (address => uint256) public contentPriceEarning;
// Mapping from address to his/her inflation bonus
mapping (address => uint256) public inflationBonusAccrued;
struct Earning {
bytes32 purchaseId;
uint256 paymentEarning;
uint256 inflationBonus;
uint256 pathosAmount;
uint256 ethosAmount;
}
// Mapping from address to earning from staking content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public stakeEarnings;
// Mapping from address to earning from hosting content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public hostEarnings;
// Mapping from purchase ID to earning for The AO
mapping (bytes32 => Earning) public theAOEarnings;
// Mapping from stake ID to it's total earning from staking
mapping (bytes32 => uint256) public totalStakedContentStakeEarning;
// Mapping from stake ID to it's total earning from hosting
mapping (bytes32 => uint256) public totalStakedContentHostEarning;
// Mapping from stake ID to it's total earning earned by The AO
mapping (bytes32 => uint256) public totalStakedContentTheAOEarning;
// Mapping from content host ID to it's total earning
mapping (bytes32 => uint256) public totalHostContentEarningById;
// Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earning is released from escrow
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content
event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when host's Name earns Ethos when a node buys a content
event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _nameFactoryAddress The address of NameFactory
* @param _pathosAddress The address of Pathos
* @param _ethosAddress The address of Ethos
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
pathosAddress = _pathosAddress;
ethosAddress = _ethosAddress;
_aoSetting = AOSetting(_aoSettingAddress);
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_nameFactory = NameFactory(_nameFactoryAddress);
_pathos = Pathos(_pathosAddress);
_ethos = Ethos(_ethosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Calculate the content creator/host/The AO earning when request node buys the content.
* Also at this stage, all of the earnings are stored in escrow
* @param _buyer The request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function calculateEarning(
address _buyer,
bytes32 _purchaseId,
uint256 _networkAmountStaked,
uint256 _primordialAmountStaked,
uint256 _primordialWeightedMultiplierStaked,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) public isContractActive inWhitelist returns (bool) {
// Split the payment earning between content creator and host and store them in escrow
_escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
// Calculate the inflation bonus earning for content creator/node/The AO in escrow
_escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
return true;
}
/**
* @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID to check
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _stakeOwner The address of the stake owner
* @param _host The address of the node that host the file
* @return true on success
*/
function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) {
// Release the earning in escrow for stake owner
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0);
// Release the earning in escrow for host
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1);
// Release the earning in escrow for The AO
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Calculate the payment split for content creator/host and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal {
(uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType);
(uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning);
_escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount);
}
/**
* @dev Calculate the inflation bonus amount
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @return the bonus network amount
*/
function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
return _networkBonus.add(_primordialBonus);
}
/**
* @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _inflationBonusAmount The amount of inflation bonus earning
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowInflationBonus(
bytes32 _purchaseId,
uint256 _inflationBonusAmount,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) internal {
(, uint256 theAOCut,) = _getSettingVariables();
if (_inflationBonusAmount > 0) {
// Store how much the content creator earns in escrow
uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.inflationBonus = _stakeOwnerInflationBonus;
require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus));
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0);
// Store how much the host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus);
require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus));
emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1);
// Store how much the The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus));
emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2);
} else {
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0);
emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1);
emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2);
}
}
/**
* @dev Release the escrowed earning for a specific purchase ID for an account
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _account The address of account that made the earning (content creator/host)
* @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO)
*/
function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal {
// Make sure the recipient type is valid
require (_recipientType >= 0 && _recipientType <= 2);
uint256 _paymentEarning;
uint256 _inflationBonus;
uint256 _totalEarning;
uint256 _pathosAmount;
uint256 _ethosAmount;
if (_recipientType == 0) {
Earning storage _earning = stakeEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_pathosAmount = _earning.pathosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning);
stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning);
totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the content creator/stake owner with some Pathos
require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount));
emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount);
} else if (_recipientType == 1) {
_earning = hostEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_ethosAmount = _earning.ethosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalHostContentEarning = totalHostContentEarning.add(_totalEarning);
hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning);
totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning);
totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the host node with some Ethos
require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount));
emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount);
} else {
_earning = theAOEarnings[_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalTheAOEarning = totalTheAOEarning.add(_totalEarning);
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning);
}
require (_baseAO.unescrowFrom(_account, _totalEarning));
emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType);
}
/**
* @dev Get setting variables
* @return inflationRate The rate to use when calculating inflation bonus
* @return theAOCut The rate to use when calculating the AO earning
* @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256) {
(uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate');
(uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut');
(uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate');
return (inflationRate, theAOCut, theAOEthosEarnedRate);
}
/**
* @dev Calculate the payment split for content creator and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @return The stake owner's earning amount
* @return The pathos earned from this transaction
*/
function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.purchaseId = _purchaseId;
// Store how much the content creator (stake owner) earns in escrow
// If content is AO Content Usage Type, stake owner earns 0%
// and all profit goes to the serving host node
_stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
// Pathos = Price X Node Share X Inflation Rate
_stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning));
emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0);
return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount);
}
/**
* @dev Calculate the payment split for host node and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _host The address of the host node
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @param _stakeOwnerEarning The stake owner's earning amount
* @return The ethos earned from this transaction
*/
function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
// Store how much the node host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.purchaseId = _purchaseId;
_hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning);
// Ethos = Price X Creator Share X Inflation Rate
_hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
if (_isAOContentUsageType) {
require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning));
} else {
// If not AO Content usage type, we want to mint to the host
require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning));
}
emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1);
return _hostEarning.ethosAmount;
}
/**
* @dev Calculate the earning for The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _pathosAmount The amount of pathos earned by stake owner
* @param _ethosAmount The amount of ethos earned by host node
*/
function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal {
(,,uint256 theAOEthosEarnedRate) = _getSettingVariables();
// Store how much The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.purchaseId = _purchaseId;
// Pathos + X% of Ethos
_theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR()));
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning));
emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2);
}
}
/**
* @title AOContent
*
* The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens
* on his/her content
*/
contract AOContent is TheAO {
using SafeMath for uint256;
uint256 public totalContents;
uint256 public totalContentHosts;
uint256 public totalStakedContents;
uint256 public totalPurchaseReceipts;
address public settingTAOId;
address public baseDenominationAddress;
address public treasuryAddress;
AOToken internal _baseAO;
AOTreasury internal _treasury;
AOEarning internal _earning;
AOSetting internal _aoSetting;
NameTAOPosition internal _nameTAOPosition;
bool public paused;
bool public killed;
struct Content {
bytes32 contentId;
address creator;
/**
* baseChallenge is the content's PUBLIC KEY
* When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY)
* so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node
* submit
*/
string baseChallenge;
uint256 fileSize;
bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content
address taoId;
bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO
uint8 updateTAOContentStateV;
bytes32 updateTAOContentStateR;
bytes32 updateTAOContentStateS;
string extraData;
}
struct StakedContent {
bytes32 stakeId;
bytes32 contentId;
address stakeOwner;
uint256 networkAmount; // total network token staked in base denomination
uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination)
uint256 primordialWeightedMultiplier;
uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000
bool active; // true if currently staked, false when unstaked
uint256 createdOnTimestamp;
}
struct ContentHost {
bytes32 contentHostId;
bytes32 stakeId;
address host;
/**
* encChallenge is the content's PUBLIC KEY unique to the host
*/
string encChallenge;
string contentDatKey;
string metadataDatKey;
}
struct PurchaseReceipt {
bytes32 purchaseId;
bytes32 contentHostId;
address buyer;
uint256 price;
uint256 amountPaidByBuyer; // total network token paid in base denomination
uint256 amountPaidByAO; // total amount paid by AO
string publicKey; // The public key provided by request node
address publicAddress; // The public address provided by request node
uint256 createdOnTimestamp;
}
// Mapping from Content index to the Content object
mapping (uint256 => Content) internal contents;
// Mapping from content ID to index of the contents list
mapping (bytes32 => uint256) internal contentIndex;
// Mapping from StakedContent index to the StakedContent object
mapping (uint256 => StakedContent) internal stakedContents;
// Mapping from stake ID to index of the stakedContents list
mapping (bytes32 => uint256) internal stakedContentIndex;
// Mapping from ContentHost index to the ContentHost object
mapping (uint256 => ContentHost) internal contentHosts;
// Mapping from content host ID to index of the contentHosts list
mapping (bytes32 => uint256) internal contentHostIndex;
// Mapping from PurchaseReceipt index to the PurchaseReceipt object
mapping (uint256 => PurchaseReceipt) internal purchaseReceipts;
// Mapping from purchase ID to index of the purchaseReceipts list
mapping (bytes32 => uint256) internal purchaseReceiptIndex;
// Mapping from buyer's content host ID to the buy ID
// To check whether or not buyer has bought/paid for a content
mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts;
// Event to be broadcasted to public when `content` is stored
event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType);
// Event to be broadcasted to public when `stakeOwner` stakes a new content
event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp);
// Event to be broadcasted to public when a node hosts a content
event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey);
// Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage
event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage);
// Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content
event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier);
// Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content
event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId);
// Event to be broadcasted to public when `stakeOwner` re-stakes an existing content
event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier);
// Event to be broadcasted to public when a request node buys a content
event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp);
// Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State
event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _earningAddress The address of AOEarning
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public {
settingTAOId = _settingTAOId;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
nameTAOPositionAddress = _nameTAOPositionAddress;
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_earning = AOEarning(_earningAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
*/
function stakeAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage));
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_aoContent,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
_profitPercentage
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
*/
function stakeCreativeCommonsContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize);
(,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_creativeCommons,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
*/
function stakeTAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
address _taoId)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (
_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize &&
_nameTAOPosition.senderIsPosition(msg.sender, _taoId)
);
(,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_taoContent,
_taoId
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Set profit percentage on existing staked content
* Will throw error if this is a Creative Commons/T(AO) Content
* @param _stakeId The ID of the staked content
* @param _profitPercentage The new value to be set
*/
function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive {
require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR());
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure we are updating profit percentage for AO Content only
// Creative Commons/T(AO) Content has 0 profit percentage
require (_isAOContentUsageType(_stakedContent.contentId));
_stakedContent.profitPercentage = _profitPercentage;
emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage);
}
/**
* @dev Set extra data on existing content
* @param _contentId The ID of the content
* @param _extraData some extra information to send to the contract for a content
*/
function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure the content creator is the same as the sender
require (_content.creator == msg.sender);
_content.extraData = _extraData;
}
/**
* @dev Return content info at a given ID
* @param _contentId The ID of the content
* @return address of the creator
* @return file size of the content
* @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @return The TAO ID for this content (if this is a T(AO) Content)
* @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO
* @return The V part of signature that is used to update the TAO Content State
* @return The R part of signature that is used to update the TAO Content State
* @return The S part of signature that is used to update the TAO Content State
* @return the extra information sent to the contract when creating a content
*/
function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
_content.updateTAOContentStateS,
_content.extraData
);
}
/**
* @dev Return content host info at a given ID
* @param _contentHostId The ID of the hosted content
* @return The ID of the staked content
* @return address of the host
* @return the dat key of the content
* @return the dat key of the content's metadata
*/
function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
return (
_contentHost.stakeId,
_contentHost.host,
_contentHost.contentDatKey,
_contentHost.metadataDatKey
);
}
/**
* @dev Return staked content information at a given ID
* @param _stakeId The ID of the staked content
* @return The ID of the content being staked
* @return address of the staked content's owner
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the profit percentage of the content
* @return status of the staked content
* @return the timestamp when the staked content was created
*/
function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
return (
_stakedContent.contentId,
_stakedContent.stakeOwner,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.active,
_stakedContent.createdOnTimestamp
);
}
/**
* @dev Unstake existing staked content and refund partial staked amount to the stake owner
* Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to
* the mininum required to pay the fileSize
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to unstake
* @param _networkFractionAmount The fraction amount of network token to unstake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to unstake
*/
function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the staked content has enough balance to unstake
require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize));
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount);
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount);
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Unstake existing staked content and refund the total staked amount to the stake owner
* @param _stakeId The ID of the staked content
*/
function unstakeContent(bytes32 _stakeId) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
_stakedContent.active = false;
if (_stakedContent.networkAmount > 0) {
uint256 _unstakeNetworkAmount = _stakedContent.networkAmount;
_stakedContent.networkAmount = 0;
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_stakedContent.primordialAmount > 0) {
uint256 _primordialAmount = _stakedContent.primordialAmount;
uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier;
_stakedContent.primordialAmount = 0;
_stakedContent.primordialWeightedMultiplier = 0;
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier));
}
emit UnstakeContent(_stakedContent.stakeOwner, _stakeId);
}
/**
* @dev Stake existing content with more tokens (this is to increase the price)
*
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier)
*/
function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount));
// Make sure we can stake primordial token
// If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier`
// i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first
if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) {
require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier);
}
_stakedContent.active = true;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount);
require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount);
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Determine the content price hosted by a host
* @param _contentHostId The content host ID to be checked
* @return the price of the content
*/
function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) {
// Make sure content host exist
require (contentHostIndex[_contentHostId] > 0);
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure content is currently staked
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
return _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
}
/**
* @dev Determine the how much the content is paid by AO given a contentHostId
* @param _contentHostId The content host ID to be checked
* @return the amount paid by AO
*/
function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) {
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
if (_isAOContentUsageType(_contentId)) {
return 0;
} else {
return contentHostPrice(_contentHostId);
}
}
/**
* @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content
* @param _contentHostId The ID of hosted content
* @param _networkIntegerAmount The integer amount of network token to pay
* @param _networkFractionAmount The fraction amount of network token to pay
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _publicKey The public key of the request node
* @param _publicAddress The public address of the request node
*/
function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
// Make sure public key is not empty
require (bytes(_publicKey).length > 0);
// Make sure public address is valid
require (_publicAddress != address(0));
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]];
// Make sure the content currently has stake
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the buyer has not bought this content previously
require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0);
// Make sure the token amount can pay for the content price
if (_isAOContentUsageType(_stakedContent.contentId)) {
require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination));
}
// Increment totalPurchaseReceipts;
totalPurchaseReceipts++;
// Generate purchaseId
bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId));
PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts];
// Make sure the node doesn't buy the same content twice
require (_purchaseReceipt.buyer == address(0));
_purchaseReceipt.purchaseId = _purchaseId;
_purchaseReceipt.contentHostId = _contentHostId;
_purchaseReceipt.buyer = msg.sender;
// Update the receipt with the correct network amount
_purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
_purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId);
_purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO);
_purchaseReceipt.publicKey = _publicKey;
_purchaseReceipt.publicAddress = _publicAddress;
_purchaseReceipt.createdOnTimestamp = now;
purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts;
buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId;
// Calculate content creator/host/The AO earning from this purchase and store them in escrow
require (_earning.calculateEarning(
msg.sender,
_purchaseId,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.stakeOwner,
_contentHost.host,
_isAOContentUsageType(_stakedContent.contentId)
));
emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp);
}
/**
* @dev Return purchase receipt info at a given ID
* @param _purchaseId The ID of the purchased content
* @return The ID of the content host
* @return address of the buyer
* @return price of the content
* @return amount paid by AO
* @return amount paid by Buyer
* @return request node's public key
* @return request node's public address
* @return created on timestamp
*/
function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
return (
_purchaseReceipt.contentHostId,
_purchaseReceipt.buyer,
_purchaseReceipt.price,
_purchaseReceipt.amountPaidByAO,
_purchaseReceipt.amountPaidByBuyer,
_purchaseReceipt.publicKey,
_purchaseReceipt.publicAddress,
_purchaseReceipt.createdOnTimestamp
);
}
/**
* @dev Request node wants to become a distribution node after buying the content
* Also, if this transaction succeeds, contract will release all of the earnings that are
* currently in escrow for content creator/host/The AO
*/
function becomeHost(
bytes32 _purchaseId,
uint8 _baseChallengeV,
bytes32 _baseChallengeR,
bytes32 _baseChallengeS,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey
) public isContractActive {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
// Make sure the purchase receipt owner is the same as the sender
require (_purchaseReceipt.buyer == msg.sender);
// Verify that the file is not tampered by validating the base challenge signature
// The signed base challenge key should match the one from content creator
Content memory _content = contents[contentIndex[_contentId]];
require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress);
_hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey);
// Release earning from escrow
require (_earning.releaseEarning(
_stakeId,
_purchaseReceipt.contentHostId,
_purchaseId,
(_purchaseReceipt.amountPaidByBuyer > _content.fileSize),
stakedContents[stakedContentIndex[_stakeId]].stakeOwner,
contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host)
);
}
/**
* @dev Update the TAO Content State of a T(AO) Content
* @param _contentId The ID of the Content
* @param _taoId The ID of the TAO that initiates the update
* @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _updateTAOContentStateV The V part of the signature for this update
* @param _updateTAOContentStateR The R part of the signature for this update
* @param _updateTAOContentStateS The S part of the signature for this update
*/
function updateTAOContentState(
bytes32 _contentId,
address _taoId,
bytes32 _taoContentState,
uint8 _updateTAOContentStateV,
bytes32 _updateTAOContentStateR,
bytes32 _updateTAOContentStateS
) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
require (AOLibrary.isTAO(_taoId));
(,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables();
require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO);
address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker
require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId));
require (_content.contentUsageType == _contentUsageType_taoContent);
_content.taoContentState = _taoContentState;
_content.updateTAOContentStateV = _updateTAOContentStateV;
_content.updateTAOContentStateR = _updateTAOContentStateR;
_content.updateTAOContentStateS = _updateTAOContentStateS;
emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState);
}
/***** INTERNAL METHODS *****/
/**
* @dev Store the content information (content creation during staking)
* @param _creator the address of the content creator
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _fileSize The size of the file
* @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
* @return the ID of the content
*/
function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) {
// Increment totalContents
totalContents++;
// Generate contentId
bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents));
Content storage _content = contents[totalContents];
// Make sure the node does't store the same content twice
require (_content.creator == address(0));
(,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables();
_content.contentId = _contentId;
_content.creator = _creator;
_content.baseChallenge = _baseChallenge;
_content.fileSize = _fileSize;
_content.contentUsageType = _contentUsageType;
// If this is a TAO Content
if (_contentUsageType == contentUsageType_taoContent) {
_content.taoContentState = taoContentState_submitted;
_content.taoId = _taoId;
}
contentIndex[_contentId] = totalContents;
emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType);
return _content.contentId;
}
/**
* @dev Add the distribution node info that hosts the content
* @param _host the address of the host
* @param _stakeId The ID of the staked content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
*/
function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal {
require (bytes(_encChallenge).length > 0);
require (bytes(_contentDatKey).length > 0);
require (bytes(_metadataDatKey).length > 0);
require (stakedContentIndex[_stakeId] > 0);
// Increment totalContentHosts
totalContentHosts++;
// Generate contentId
bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId));
ContentHost storage _contentHost = contentHosts[totalContentHosts];
// Make sure the node doesn't host the same content twice
require (_contentHost.host == address(0));
_contentHost.contentHostId = _contentHostId;
_contentHost.stakeId = _stakeId;
_contentHost.host = _host;
_contentHost.encChallenge = _encChallenge;
_contentHost.contentDatKey = _contentDatKey;
_contentHost.metadataDatKey = _metadataDatKey;
contentHostIndex[_contentHostId] = totalContentHosts;
emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey);
}
/**
* @dev actual staking the content
* @param _stakeOwner the address that stake the content
* @param _contentId The ID of the content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return the newly created staked content ID
*/
function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) {
// Increment totalStakedContents
totalStakedContents++;
// Generate stakeId
bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId));
StakedContent storage _stakedContent = stakedContents[totalStakedContents];
// Make sure the node doesn't stake the same content twice
require (_stakedContent.stakeOwner == address(0));
_stakedContent.stakeId = _stakeId;
_stakedContent.contentId = _contentId;
_stakedContent.stakeOwner = _stakeOwner;
_stakedContent.profitPercentage = _profitPercentage;
_stakedContent.active = true;
_stakedContent.createdOnTimestamp = now;
stakedContentIndex[_stakeId] = totalStakedContents;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
_stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _primordialAmount;
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp);
return _stakedContent.stakeId;
}
/**
* @dev Get setting variables
* @return contentUsageType_aoContent Content Usage Type = AO Content
* @return contentUsageType_creativeCommons Content Usage Type = Creative Commons
* @return contentUsageType_taoContent Content Usage Type = T(AO) Content
* @return taoContentState_submitted TAO Content State = Submitted
* @return taoContentState_pendingReview TAO Content State = Pending Review
* @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO
*/
function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {
(,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent');
(,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons');
(,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent');
(,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted');
(,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview');
(,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO');
return (
contentUsageType_aoContent,
contentUsageType_creativeCommons,
contentUsageType_taoContent,
taoContentState_submitted,
taoContentState_pendingReview,
taoContentState_acceptedToTAO
);
}
/**
* @dev Check whether or not the content is of AO Content Usage Type
* @param _contentId The ID of the content
* @return true if yes. false otherwise
*/
function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) {
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
contract Logos is TAOCurrency {
NameTAOPosition internal _nameTAOPosition;
// Mapping of a Name ID to the amount of Logos positioned by others to itself
// address is the address of nameId, not the eth public address
mapping (address => uint256) public positionFromOthers;
// Mapping of Name ID to other Name ID and the amount of Logos positioned by itself
mapping (address => mapping(address => uint256)) public positionToOthers;
// Mapping of a Name ID to the total amount of Logos positioned by itself to others
mapping (address => uint256) public totalPositionToOthers;
// Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned
mapping (address => mapping(address => uint256)) public advocatedTAOLogos;
// Mapping of a Name ID to the total amount of Logos earned from advocated TAO
mapping (address => uint256) public totalAdvocatedTAOLogos;
// Event broadcasted to public when `from` address position `value` Logos to `to`
event PositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `from` address unposition `value` Logos from `to`
event UnpositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId`
event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount);
// Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId`
event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of _id
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get the total sum of Logos for an address
* @param _target The address to check
* @return The total sum of Logos (own + positioned + advocated TAOs)
*/
function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) {
return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]);
}
/**
* @dev `_from` Name position `_value` Logos onto `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to position
* @return true on success
*/
function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't position Logos to itself
require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position
require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value);
positionFromOthers[_to] = positionFromOthers[_to].add(_value);
emit PositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance);
return true;
}
/**
* @dev `_from` Name unposition `_value` Logos from `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to unposition
* @return true on success
*/
function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't unposition Logos to itself
require (positionToOthers[_from][_to] >= _value);
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value);
positionFromOthers[_to] = positionFromOthers[_to].sub(_value);
emit UnpositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance);
return true;
}
/**
* @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate
* @param _taoId The ID of the advocated TAO
* @param _amount the amount to reward
* @return true on success
*/
function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) {
require (_amount > 0);
address _nameId = _nameTAOPosition.getAdvocate(_taoId);
advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount);
emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount);
return true;
}
/**
* @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId`
* @param _fromNameId The ID of the Name that sends the Logos
* @param _toNameId The ID of the Name that receives the Logos
* @param _taoId The ID of the advocated TAO
* @return true on success
*/
function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) {
require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId));
require (advocatedTAOLogos[_fromNameId][_taoId] > 0);
require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]);
uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId];
advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount);
totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount);
advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount);
emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount);
return true;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev Check whether or not content creator can stake a content based on the provided params
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return true if yes. false otherwise
*/
function canStake(address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage) public view returns (bool) {
return (
bytes(_baseChallenge).length > 0 &&
bytes(_encChallenge).length > 0 &&
bytes(_contentDatKey).length > 0 &&
bytes(_metadataDatKey).length > 0 &&
_fileSize > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) &&
_stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true &&
_profitPercentage <= _PERCENTAGE_DIVISOR
);
}
/**
* @dev Check whether or the requested unstake amount is valid
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @param _stakedNetworkAmount The current staked network token amount
* @param _stakedPrimordialAmount The current staked primordial token amount
* @param _stakedFileSize The file size of the staked content
* @return true if can unstake, false otherwise
*/
function canUnstakePartial(
address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
uint256 _stakedNetworkAmount,
uint256 _stakedPrimordialAmount,
uint256 _stakedFileSize) public view returns (bool) {
if (
(_denomination.length > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0) &&
_stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)
) ||
_stakedPrimordialAmount < _primordialAmount ||
(
_denomination.length > 0
&& (_networkIntegerAmount > 0 || _networkFractionAmount > 0)
&& (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize)
) ||
( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize)
) {
return false;
} else {
return true;
}
}
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _isAOContentUsageType whether or not the content is of AO Content usage type
* @param _fileSize The size of the file
* @param _stakedAmount The total staked amount
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @return true when the amount is sufficient, false otherwise
*/
function canStakeExisting(
address _treasuryAddress,
bool _isAOContentUsageType,
uint256 _fileSize,
uint256 _stakedAmount,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount
) public view returns (bool) {
if (_isAOContentUsageType) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize;
} else {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize;
}
}
/**
* @dev Check whether the network token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _price The price of the content
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @return true when the amount is sufficient, false otherwise
*/
function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price;
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial token balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial token amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedTokens.div(_totalTokens);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Return the address that signed the message when a node wants to become a host
* @param _callingContractAddress the address of the calling contract
* @param _message the message that was signed
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the address that signed the TAO content state update
* @param _callingContractAddress the address of the calling contract
* @param _contentId the ID of the content
* @param _taoId the ID of the TAO
* @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the staking and earning information of a stake ID
* @param _contentAddress The address of AOContent
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId);
(uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier,
totalStakeEarning,
totalHostEarning,
totalTheAOEarning
);
}
/**
* @dev Return the staking information of a stake ID
* @param _contentAddress The address of AOContent
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
*/
function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
(,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier
);
}
/**
* @dev Return the earning information of a stake ID
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
return (
AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId)
);
}
/**
* @dev Calculate the primordial token multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network token on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Token Bonus Multiplier = Bs
* Ending Network Token Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network token on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network token bonus amount
*/
uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkTokenBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network token to primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev Get TAO Currency Balances given a nameId
* @param _nameId The ID of the Name
* @param _logosAddress The address of Logos
* @param _ethosAddress The address of Ethos
* @param _pathosAddress The address of Pathos
* @return sum Logos balance of the Name ID
* @return Ethos balance of the Name ID
* @return Pathos balance of the Name ID
*/
function getTAOCurrencyBalances(
address _nameId,
address _logosAddress,
address _ethosAddress,
address _pathosAddress
) public view returns (uint256, uint256, uint256) {
return (
Logos(_logosAddress).sumBalanceOf(_nameId),
TAOCurrency(_ethosAddress).balanceOf(_nameId),
TAOCurrency(_pathosAddress).balanceOf(_nameId)
);
}
/**
* @dev Return the address that signed the data and nonce when validating signature
* @param _callingContractAddress the address of the calling contract
* @param _data the data that was signed
* @param _nonce The signed uint256 nonce
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce));
return ecrecover(_hash, _v, _r, _s);
}
/***** Internal Methods *****/
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for the filesize
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _fileSize The size of the file
* @return true when the amount is sufficient, false otherwise
*/
function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize;
}
}
contract Epiphany is TheAO {
string public what;
string public when;
string public why;
string public who;
address public where;
string public aSign;
string public logos;
constructor() public {
what = 'The AO';
when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.';
why = 'To Hear, See, and Speak the Human inside Humanity.';
who = 'You. Set the world, Free. – Truth';
aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf';
logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32';
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Set `where` value
* @param _where The new value to be set
*/
function setWhere(address _where) public onlyTheAO {
where = _where;
}
}
|
Get setting variables return inflationRate The rate to use when calculating inflation bonus return theAOCut The rate to use when calculating the AO earning return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO/
|
function _getSettingVariables() internal view returns (uint256, uint256, uint256) {
(uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate');
(uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut');
(uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate');
return (inflationRate, theAOCut, theAOEthosEarnedRate);
}
| 10,007,535
|
pragma solidity ^0.4.18;
// File: contracts\configs\FabricTokenConfig.sol
/**
* @title FabricTokenConfig
*
* @dev The static configuration for the Fabric Token.
*/
contract FabricTokenConfig {
// The name of the token.
string constant NAME = "Fabric Token";
// The symbol of the token.
string constant SYMBOL = "FT";
// The number of decimals for the token.
uint8 constant DECIMALS = 18; // Same as ethers.
// Decimal factor for multiplication purposes.
uint constant DECIMALS_FACTOR = 10 ** uint(DECIMALS);
}
// File: contracts\interfaces\ERC20TokenInterface.sol
/**
* @dev The standard ERC20 Token interface.
*/
contract ERC20TokenInterface {
uint public totalSupply; /* shorthand for public function and a property */
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
}
// File: contracts\libraries\SafeMath.sol
/**
* @dev Library that helps prevent integer overflows and underflows,
* inspired by https://github.com/OpenZeppelin/zeppelin-solidity
*/
library SafeMath {
function plus(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function minus(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
}
// File: contracts\traits\ERC20Token.sol
/**
* @title ERC20Token
*
* @dev Implements the operations declared in the `ERC20TokenInterface`.
*/
contract ERC20Token is ERC20TokenInterface {
using SafeMath for uint;
// Token account balances.
mapping (address => uint) balances;
// Delegated number of tokens to transfer.
mapping (address => mapping (address => uint)) allowed;
/**
* @dev Checks the balance of a certain address.
*
* @param _account The address which's balance will be checked.
*
* @return Returns the balance of the `_account` address.
*/
function balanceOf(address _account) public constant returns (uint balance) {
return balances[_account];
}
/**
* @dev Transfers tokens from one address to another.
*
* @param _to The target address to which the `_value` number of tokens will be sent.
* @param _value The number of tokens to send.
*
* @return Whether the transfer was successful or not.
*/
function transfer(address _to, uint _value) public returns (bool success) {
if (balances[msg.sender] < _value || _value == 0) {
return false;
}
balances[msg.sender] -= _value;
balances[_to] = balances[_to].plus(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Send `_value` tokens to `_to` from `_from` if `_from` has approved the process.
*
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The number of tokens to be transferred.
*
* @return Whether the transfer was successful or not.
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
if (balances[_from] < _value || allowed[_from][msg.sender] < _value || _value == 0) {
return false;
}
balances[_to] = balances[_to].plus(_value);
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Allows another contract to spend some tokens on your behalf.
*
* @param _spender The address of the account which will be approved for transfer of tokens.
* @param _value The number of tokens to be approved for transfer.
*
* @return Whether the approval was successful or not.
*/
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Shows the number of tokens approved by `_owner` that are allowed to be transferred by `_spender`.
*
* @param _owner The account which allowed the transfer.
* @param _spender The account which will spend the tokens.
*
* @return The number of tokens to be transferred.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
// File: contracts\traits\HasOwner.sol
/**
* @title HasOwner
*
* @dev Allows for exclusive access to certain functionality.
*/
contract HasOwner {
// Current owner.
address public owner;
// Conditionally the new owner.
address public newOwner;
/**
* @dev The constructor.
*
* @param _owner The address of the owner.
*/
function HasOwner(address _owner) internal {
owner = _owner;
}
/**
* @dev Access control modifier that allows only the current owner to call the function.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev The event is fired when the current owner is changed.
*
* @param _oldOwner The address of the previous owner.
* @param _newOwner The address of the new owner.
*/
event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner);
/**
* @dev Transfering the ownership is a two-step process, as we prepare
* for the transfer by setting `newOwner` and requiring `newOwner` to accept
* the transfer. This prevents accidental lock-out if something goes wrong
* when passing the `newOwner` address.
*
* @param _newOwner The address of the proposed new owner.
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev The `newOwner` finishes the ownership transfer process by accepting the
* ownership.
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransfer(owner, newOwner);
owner = newOwner;
}
}
// File: contracts\traits\Freezable.sol
/**
* @title Freezable
* @dev This trait allows to freeze the transactions in a Token
*/
contract Freezable is HasOwner {
bool public frozen = false;
/**
* @dev Modifier makes methods callable only when the contract is not frozen.
*/
modifier requireNotFrozen() {
require(!frozen);
_;
}
/**
* @dev Allows the owner to "freeze" the contract.
*/
function freeze() onlyOwner public {
frozen = true;
}
/**
* @dev Allows the owner to "unfreeze" the contract.
*/
function unfreeze() onlyOwner public {
frozen = false;
}
}
// File: contracts\traits\FreezableERC20Token.sol
/**
* @title FreezableERC20Token
*
* @dev Extends ERC20Token and adds ability to freeze all transfers of tokens.
*/
contract FreezableERC20Token is ERC20Token, Freezable {
/**
* @dev Overrides the original ERC20Token implementation by adding whenNotFrozen modifier.
*
* @param _to The target address to which the `_value` number of tokens will be sent.
* @param _value The number of tokens to send.
*
* @return Whether the transfer was successful or not.
*/
function transfer(address _to, uint _value) public requireNotFrozen returns (bool success) {
return super.transfer(_to, _value);
}
/**
* @dev Send `_value` tokens to `_to` from `_from` if `_from` has approved the process.
*
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The number of tokens to be transferred.
*
* @return Whether the transfer was successful or not.
*/
function transferFrom(address _from, address _to, uint _value) public requireNotFrozen returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Allows another contract to spend some tokens on your behalf.
*
* @param _spender The address of the account which will be approved for transfer of tokens.
* @param _value The number of tokens to be approved for transfer.
*
* @return Whether the approval was successful or not.
*/
function approve(address _spender, uint _value) public requireNotFrozen returns (bool success) {
return super.approve(_spender, _value);
}
}
// File: contracts\FabricToken.sol
/**
* @title Fabric Token
*
* @dev A standard token implementation of the ERC20 token standard with added
* HasOwner trait and initialized using the configuration constants.
*/
contract FabricToken is FabricTokenConfig, HasOwner, FreezableERC20Token {
// The name of the token.
string public name;
// The symbol for the token.
string public symbol;
// The decimals of the token.
uint8 public decimals;
/**
* @dev The constructor. Initially sets `totalSupply` and the balance of the
* `owner` address according to the initialization parameter.
*/
function FabricToken(uint _totalSupply) public
HasOwner(msg.sender)
{
name = NAME;
symbol = SYMBOL;
decimals = DECIMALS;
totalSupply = _totalSupply;
balances[owner] = _totalSupply;
}
}
// File: contracts\configs\FabricTokenFundraiserConfig.sol
/**
* @title FabricTokenFundraiserConfig
*
* @dev The static configuration for the Fabric Token fundraiser.
*/
contract FabricTokenFundraiserConfig is FabricTokenConfig {
// The number of FT per 1 ETH.
uint constant CONVERSION_RATE = 9000;
// The public sale hard cap of the fundraiser.
uint constant TOKENS_HARD_CAP = 71250 * (10**3) * DECIMALS_FACTOR;
// The start date of the fundraiser: Thursday, 2018-02-15 10:00:00 UTC.
uint constant START_DATE = 1518688800;
// The end date of the fundraiser: Sunday, 2018-04-01 10:00:00 UTC (45 days after `START_DATE`).
uint constant END_DATE = 1522576800;
// Total number of tokens locked for the FT core team.
uint constant TOKENS_LOCKED_CORE_TEAM = 12 * (10**6) * DECIMALS_FACTOR;
// Total number of tokens locked for FT advisors.
uint constant TOKENS_LOCKED_ADVISORS = 7 * (10**6) * DECIMALS_FACTOR;
// The release date for tokens locked for the FT core team.
uint constant TOKENS_LOCKED_CORE_TEAM_RELEASE_DATE = START_DATE + 1 years;
// The release date for tokens locked for FT advisors.
uint constant TOKENS_LOCKED_ADVISORS_RELEASE_DATE = START_DATE + 180 days;
// Total number of tokens locked for bounty program.
uint constant TOKENS_BOUNTY_PROGRAM = 1 * (10**6) * DECIMALS_FACTOR;
// Maximum gas price limit
uint constant MAX_GAS_PRICE = 50000000000 wei; // 50 gwei/shanon
// Minimum individual contribution
uint constant MIN_CONTRIBUTION = 0.1 ether;
// Individual limit in ether
uint constant INDIVIDUAL_ETHER_LIMIT = 9 ether;
}
// File: contracts\traits\TokenSafe.sol
/**
* @title TokenSafe
*
* @dev A multi-bundle token safe contract that contains locked tokens released after a date for the specific bundle type.
*/
contract TokenSafe {
using SafeMath for uint;
struct AccountsBundle {
// The total number of tokens locked.
uint lockedTokens;
// The release date for the locked tokens
// Note: Unix timestamp fits uint32, however block.timestamp is uint
uint releaseDate;
// The balances for the FT locked token accounts.
mapping (address => uint) balances;
}
// The account bundles of locked tokens grouped by release date
mapping (uint8 => AccountsBundle) public bundles;
// The `ERC20TokenInterface` contract.
ERC20TokenInterface token;
/**
* @dev The constructor.
*
* @param _token The address of the Fabric Token (fundraiser) contract.
*/
function TokenSafe(address _token) public {
token = ERC20TokenInterface(_token);
}
/**
* @dev The function initializes the bundle of accounts with a release date.
*
* @param _type Bundle type.
* @param _releaseDate Unix timestamp of the time after which the tokens can be released
*/
function initBundle(uint8 _type, uint _releaseDate) internal {
bundles[_type].releaseDate = _releaseDate;
}
/**
* @dev Add new account with locked token balance to the specified bundle type.
*
* @param _type Bundle type.
* @param _account The address of the account to be added.
* @param _balance The number of tokens to be locked.
*/
function addLockedAccount(uint8 _type, address _account, uint _balance) internal {
var bundle = bundles[_type];
bundle.balances[_account] = bundle.balances[_account].plus(_balance);
bundle.lockedTokens = bundle.lockedTokens.plus(_balance);
}
/**
* @dev Allows an account to be released if it meets the time constraints.
*
* @param _type Bundle type.
* @param _account The address of the account to be released.
*/
function releaseAccount(uint8 _type, address _account) internal {
var bundle = bundles[_type];
require(now >= bundle.releaseDate);
uint tokens = bundle.balances[_account];
require(tokens > 0);
bundle.balances[_account] = 0;
bundle.lockedTokens = bundle.lockedTokens.minus(tokens);
if (!token.transfer(_account, tokens)) {
revert();
}
}
}
// File: contracts\FabricTokenSafe.sol
/**
* @title FabricTokenSafe
*
* @dev The Fabric Token safe containing all details about locked tokens.
*/
contract FabricTokenSafe is TokenSafe, FabricTokenFundraiserConfig {
// Bundle type constants
uint8 constant CORE_TEAM = 0;
uint8 constant ADVISORS = 1;
/**
* @dev The constructor.
*
* @param _token The address of the Fabric Token (fundraiser) contract.
*/
function FabricTokenSafe(address _token) public
TokenSafe(_token)
{
token = ERC20TokenInterface(_token);
/// Core team.
initBundle(CORE_TEAM,
TOKENS_LOCKED_CORE_TEAM_RELEASE_DATE
);
// Accounts with tokens locked for the FT core team.
addLockedAccount(CORE_TEAM, 0xB494096548aA049C066289A083204E923cBf4413, 4 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(CORE_TEAM, 0xE3506B01Bee377829ee3CffD8bae650e990c5d68, 4 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(CORE_TEAM, 0x3d13219dc1B8913E019BeCf0772C2a54318e5718, 4 * (10**6) * DECIMALS_FACTOR);
// Verify that the tokens add up to the constant in the configuration.
assert(bundles[CORE_TEAM].lockedTokens == TOKENS_LOCKED_CORE_TEAM);
/// Advisors.
initBundle(ADVISORS,
TOKENS_LOCKED_ADVISORS_RELEASE_DATE
);
// Accounts with FT tokens locked for advisors.
addLockedAccount(ADVISORS, 0x4647Da07dAAb17464278B988CDE59A4b911EBe44, 2 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(ADVISORS, 0x3eA2caac5A0A4a55f9e304AcD09b3CEe6cD4Bc39, 1 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(ADVISORS, 0xd5f791EC3ED79f79a401b12f7625E1a972382437, 1 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(ADVISORS, 0xcaeae3CD1a5d3E6E950424C994e14348ac3Ec5dA, 1 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(ADVISORS, 0xb6EA6193058F3c8A4A413d176891d173D62E00bE, 1 * (10**6) * DECIMALS_FACTOR);
addLockedAccount(ADVISORS, 0x8b3E184Cf5C3bFDaB1C4D0F30713D30314FcfF7c, 1 * (10**6) * DECIMALS_FACTOR);
// Verify that the tokens add up to the constant in the configuration.
assert(bundles[ADVISORS].lockedTokens == TOKENS_LOCKED_ADVISORS);
}
/**
* @dev Returns the total locked tokens. This function is called by the fundraiser to determine number of tokens to create upon finalization.
*
* @return The current total number of locked Fabric Tokens.
*/
function totalTokensLocked() public constant returns (uint) {
return bundles[CORE_TEAM].lockedTokens.plus(bundles[ADVISORS].lockedTokens);
}
/**
* @dev Allows core team account FT tokens to be released.
*/
function releaseCoreTeamAccount() public {
releaseAccount(CORE_TEAM, msg.sender);
}
/**
* @dev Allows advisors account FT tokens to be released.
*/
function releaseAdvisorsAccount() public {
releaseAccount(ADVISORS, msg.sender);
}
}
// File: contracts\traits\Whitelist.sol
contract Whitelist is HasOwner
{
// Whitelist mapping
mapping(address => bool) public whitelist;
/**
* @dev The constructor.
*/
function Whitelist(address _owner) public
HasOwner(_owner)
{
}
/**
* @dev Access control modifier that allows only whitelisted address to call the method.
*/
modifier onlyWhitelisted {
require(whitelist[msg.sender]);
_;
}
/**
* @dev Internal function that sets whitelist status in batch.
*
* @param _entries An array with the entries to be updated
* @param _status The new status to apply
*/
function setWhitelistEntries(address[] _entries, bool _status) internal {
for (uint32 i = 0; i < _entries.length; ++i) {
whitelist[_entries[i]] = _status;
}
}
/**
* @dev Public function that allows the owner to whitelist multiple entries
*
* @param _entries An array with the entries to be whitelisted
*/
function whitelistAddresses(address[] _entries) public onlyOwner {
setWhitelistEntries(_entries, true);
}
/**
* @dev Public function that allows the owner to blacklist multiple entries
*
* @param _entries An array with the entries to be blacklist
*/
function blacklistAddresses(address[] _entries) public onlyOwner {
setWhitelistEntries(_entries, false);
}
}
// File: contracts\FabricTokenFundraiser.sol
/**
* @title FabricTokenFundraiser
*
* @dev The Fabric Token fundraiser contract.
*/
contract FabricTokenFundraiser is FabricToken, FabricTokenFundraiserConfig, Whitelist {
// Indicates whether the fundraiser has ended or not.
bool public finalized = false;
// The address of the account which will receive the funds gathered by the fundraiser.
address public beneficiary;
// The number of FT participants will receive per 1 ETH.
uint public conversionRate;
// Fundraiser start date.
uint public startDate;
// Fundraiser end date.
uint public endDate;
// Fundraiser tokens hard cap.
uint public hardCap;
// The `FabricTokenSafe` contract.
FabricTokenSafe public fabricTokenSafe;
// The minimum amount of ether allowed in the public sale
uint internal minimumContribution;
// The maximum amount of ether allowed per address
uint internal individualLimit;
// Number of tokens sold during the fundraiser.
uint private tokensSold;
// Indicates whether the tokens are claimed by the partners
bool private partnerTokensClaimed = false;
/**
* @dev The event fires every time a new buyer enters the fundraiser.
*
* @param _address The address of the buyer.
* @param _ethers The number of ethers sent.
* @param _tokens The number of tokens received by the buyer.
* @param _newTotalSupply The updated total number of tokens currently in circulation.
* @param _conversionRate The conversion rate at which the tokens were bought.
*/
event FundsReceived(address indexed _address, uint _ethers, uint _tokens, uint _newTotalSupply, uint _conversionRate);
/**
* @dev The event fires when the beneficiary of the fundraiser is changed.
*
* @param _beneficiary The address of the new beneficiary.
*/
event BeneficiaryChange(address _beneficiary);
/**
* @dev The event fires when the number of FT per 1 ETH is changed.
*
* @param _conversionRate The new number of FT per 1 ETH.
*/
event ConversionRateChange(uint _conversionRate);
/**
* @dev The event fires when the fundraiser is successfully finalized.
*
* @param _beneficiary The address of the beneficiary.
* @param _ethers The number of ethers transfered to the beneficiary.
* @param _totalSupply The total number of tokens in circulation.
*/
event Finalized(address _beneficiary, uint _ethers, uint _totalSupply);
/**
* @dev The constructor.
*
* @param _beneficiary The address which will receive the funds gathered by the fundraiser.
*/
function FabricTokenFundraiser(address _beneficiary) public
FabricToken(0)
Whitelist(msg.sender)
{
require(_beneficiary != 0);
beneficiary = _beneficiary;
conversionRate = CONVERSION_RATE;
startDate = START_DATE;
endDate = END_DATE;
hardCap = TOKENS_HARD_CAP;
tokensSold = 0;
minimumContribution = MIN_CONTRIBUTION;
individualLimit = INDIVIDUAL_ETHER_LIMIT * CONVERSION_RATE;
fabricTokenSafe = new FabricTokenSafe(this);
// Freeze the transfers for the duration of the fundraiser.
freeze();
}
/**
* @dev Changes the beneficiary of the fundraiser.
*
* @param _beneficiary The address of the new beneficiary.
*/
function setBeneficiary(address _beneficiary) public onlyOwner {
require(_beneficiary != 0);
beneficiary = _beneficiary;
BeneficiaryChange(_beneficiary);
}
/**
* @dev Sets converstion rate of 1 ETH to FT. Can only be changed before the fundraiser starts.
*
* @param _conversionRate The new number of Fabric Tokens per 1 ETH.
*/
function setConversionRate(uint _conversionRate) public onlyOwner {
require(now < startDate);
require(_conversionRate > 0);
conversionRate = _conversionRate;
individualLimit = INDIVIDUAL_ETHER_LIMIT * _conversionRate;
ConversionRateChange(_conversionRate);
}
/**
* @dev The default function which will fire every time someone sends ethers to this contract's address.
*/
function() public payable {
buyTokens();
}
/**
* @dev Creates new tokens based on the number of ethers sent and the conversion rate.
*/
function buyTokens() public payable onlyWhitelisted {
require(!finalized);
require(now >= startDate);
require(now <= endDate);
require(tx.gasprice <= MAX_GAS_PRICE); // gas price limit
require(msg.value >= minimumContribution); // required minimum contribution
require(tokensSold <= hardCap);
// Calculate the number of tokens the buyer will receive.
uint tokens = msg.value.mul(conversionRate);
balances[msg.sender] = balances[msg.sender].plus(tokens);
// Ensure that the individual contribution limit has not been reached
require(balances[msg.sender] <= individualLimit);
tokensSold = tokensSold.plus(tokens);
totalSupply = totalSupply.plus(tokens);
Transfer(0x0, msg.sender, tokens);
FundsReceived(
msg.sender,
msg.value,
tokens,
totalSupply,
conversionRate
);
}
/**
* @dev Distributes the tokens allocated for the strategic partners.
*/
function claimPartnerTokens() public {
require(!partnerTokensClaimed);
require(now >= startDate);
partnerTokensClaimed = true;
address partner1 = 0xA6556B9BD0AAbf0d8824374A3C425d315b09b832;
balances[partner1] = balances[partner1].plus(125 * (10**4) * DECIMALS_FACTOR);
address partner2 = 0x783A1cBc37a8ef2F368908490b72BfE801DA1877;
balances[partner2] = balances[partner2].plus(750 * (10**4) * DECIMALS_FACTOR);
totalSupply = totalSupply.plus(875 * (10**4) * DECIMALS_FACTOR);
}
/**
* @dev Finalize the fundraiser if `endDate` has passed or if `hardCap` is reached.
*/
function finalize() public onlyOwner {
require((totalSupply >= hardCap) || (now >= endDate));
require(!finalized);
Finalized(beneficiary, this.balance, totalSupply);
/// Send the total number of ETH gathered to the beneficiary.
beneficiary.transfer(this.balance);
/// Allocate locked tokens to the `FabricTokenSafe` contract.
uint totalTokensLocked = fabricTokenSafe.totalTokensLocked();
balances[address(fabricTokenSafe)] = balances[address(fabricTokenSafe)].plus(totalTokensLocked);
totalSupply = totalSupply.plus(totalTokensLocked);
// Transfer the funds for the bounty program.
balances[owner] = balances[owner].plus(TOKENS_BOUNTY_PROGRAM);
totalSupply = totalSupply.plus(TOKENS_BOUNTY_PROGRAM);
/// Finalize the fundraiser. Keep in mind that this cannot be undone.
finalized = true;
// Unfreeze transfers
unfreeze();
}
}
|
Transfer the funds for the bounty program. Unfreeze transfers
|
function finalize() public onlyOwner {
require((totalSupply >= hardCap) || (now >= endDate));
require(!finalized);
Finalized(beneficiary, this.balance, totalSupply);
beneficiary.transfer(this.balance);
uint totalTokensLocked = fabricTokenSafe.totalTokensLocked();
balances[address(fabricTokenSafe)] = balances[address(fabricTokenSafe)].plus(totalTokensLocked);
totalSupply = totalSupply.plus(totalTokensLocked);
balances[owner] = balances[owner].plus(TOKENS_BOUNTY_PROGRAM);
totalSupply = totalSupply.plus(TOKENS_BOUNTY_PROGRAM);
finalized = true;
unfreeze();
}
| 12,626,857
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pragma solidity ^0.4.19;
import "./SafeMath.sol";
import "./Owned.sol";
import "./ERC20Interface.sol";
contract VotingToken is ERC20Interface, Owned {
using SafeMath for uint;
// ------------------------------------------------------------------------
// ERC 20 fields
// ------------------------------------------------------------------------
string public symbol;
string public name;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Fields required for the referendum
// ------------------------------------------------------------------------
Description public description;
Props public props;
Reward public reward;
bool public open;
struct Description {
string question;
string firstProp;
string secondProp;
}
struct Props {
address firstPropAddress;
address secondPropAddress;
address blankVoteAddress;
}
struct Reward {
address tokenAddress;
address refundWalletAddress;
}
event VoteRewarded(address indexed to, uint amount);
event Finish(string question,
string firstProp, uint firstPropCount,
string secondProp, uint secondPropCount, uint blankVoteCount);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function VotingToken(
string _symbol, string _name, uint _totalSupply,
string _question, string _firstProp, string _secondProp,
address _firstPropAddress, address _secondPropAddress, address _blankVoteAddress,
address _tokenAddress) public {
symbol = _symbol;
name = _name;
decimals = 8;
totalSupply = _totalSupply;
balances[owner] = _totalSupply;
Transfer(address(0), owner, totalSupply);
description = Description(_question, _firstProp, _secondProp);
props = Props(_firstPropAddress, _secondPropAddress, _blankVoteAddress);
reward = Reward(_tokenAddress, owner);
open = true;
}
function close() public onlyOwner returns (bool success) {
require(open);
open = false;
Finish(description.question,
description.firstProp, balanceOf(props.firstPropAddress),
description.firstProp, balanceOf(props.secondPropAddress),
balanceOf(props.blankVoteAddress));
ERC20Interface rewardToken = ERC20Interface(reward.tokenAddress);
uint leftBalance = rewardToken.balanceOf(address(this));
rewardToken.transfer(reward.refundWalletAddress, leftBalance);
return true;
}
function updateRefundWalletAddress(address _wallet) public onlyOwner returns (bool success) {
reward.refundWalletAddress = _wallet;
return true;
}
function getResults() public view returns (uint firstPropCount, uint secondPropCount, uint blankVoteCount) {
return (
balanceOf(props.firstPropAddress),
balanceOf(props.secondPropAddress),
balanceOf(props.blankVoteAddress));
}
function totalSupply() public constant returns (uint) {
return totalSupply - balances[address(0)];
}
function balanceOf(address _tokenOwner) public constant returns (uint balance) {
return balances[_tokenOwner];
}
function rewardVote(address _from, address _to, uint _tokens) private {
if(_to == props.firstPropAddress ||
_to == props.secondPropAddress ||
_to == props.blankVoteAddress) {
ERC20Interface rewardToken = ERC20Interface(reward.tokenAddress);
uint rewardTokens = _tokens.div(100);
rewardToken.transfer(_from, rewardTokens);
VoteRewarded(_from, _tokens);
}
}
// ------------------------------------------------------------------------
// 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) {
return transferFrom(msg.sender, to, tokens);
}
// ------------------------------------------------------------------------
// 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) {
require(open);
balances[from] = balances[from].sub(tokens);
if(from != msg.sender) {
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
}
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
rewardVote(from, 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) {
require(open);
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
}
|
------------------------------------------------------------------------ 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) {
return transferFrom(msg.sender, to, tokens);
}
| 895,885
|
./full_match/1/0x0e26DbA3251EaFa86f5c1419D4830C69624d26c6/sources/contracts/GuiserStake/GuiserFlexibleStake.sol
|
Stop rewards, withdraw all reward Only callable by owner. Needs to be for emergency./
|
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require(_amount <= rewardTreasure, "Exceed withdrawable amount");
wGUISEToken.safeTransfer(address(msg.sender), _amount);
rewardTreasure -= _amount;
}
| 17,085,307
|
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "../interfaces/Gauge.sol";
import "../interfaces/ICurveFiWbtc.sol";
import "../../../uniswap/interfaces/IUniswapV2Router02.sol";
contract CRVStrategyWBTCPure is Ownable {
enum TokenIndex {REN_BTC, WBTC}
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// wbtc asset
address public wbtc;
// the matching enum record used to determine the index
TokenIndex tokenIndex;
// our vault holding the wbtc asset
address public vault;
// our vault for depositing the mixToken tokens
address public mixVault;
// the address of mixToken token
address public mixToken;
// the address of the Curve protocol
address public curve;
// these tokens cannot be claimed by the governance
mapping(address => bool) public unsalvagableTokens;
// the wbtc gauge in Curve
address public pool;
address public mintr;
address public crv;
address public uni;
uint256 public wbtcPriceCheckpoint;
uint256 public mixTokenUnit;
uint256 public arbTolerance = 3;
address[] public uniswap_CRV2WBTC;
event D(string x, uint256 v);
address public underlying;
constructor(
address _storage,
address _wbtc,
address _vault,
uint256 _tokenIndex,
address _mixToken,
address _curveProtocol,
address _crv,
address _weth,
address _pool,
address _mintr,
address _uniswap
) public {
vault = _vault;
wbtc = _wbtc;
underlying = _wbtc;
tokenIndex = TokenIndex(_tokenIndex);
mixToken = _mixToken;
curve = _curveProtocol;
pool = _pool;
crv = _crv;
uni = _uniswap;
mintr = _mintr;
uniswap_CRV2WBTC = [_crv, _weth, _wbtc];
// set these tokens to be not salvageable
unsalvagableTokens[wbtc] = true;
unsalvagableTokens[mixToken] = true;
unsalvagableTokens[_crv] = true;
mixTokenUnit = 10 ** 18;
// starting with a stable price, the mainnet will override this value
wbtcPriceCheckpoint = mixTokenUnit;
}
function depositArbCheck() public view returns(bool) {
uint256 currentPrice = wbtcValueFromMixToken(mixTokenUnit);
if (currentPrice > wbtcPriceCheckpoint) {
return currentPrice.mul(100).div(wbtcPriceCheckpoint) > 100 - arbTolerance;
} else {
return wbtcPriceCheckpoint.mul(100).div(currentPrice) > 100 - arbTolerance;
}
}
function setArbTolerance(uint256 tolerance) external onlyOwner {
require(tolerance <= 100, "at most 100");
arbTolerance = tolerance;
}
/**
* Uses the Curve protocol to convert the wbtc asset into yAsset and then to mixToken.
*/
function mixFromWBTC() internal {
uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this));
emit D("mixFromWBTC wbtcBalance to make mix", wbtcBalance);
if (wbtcBalance > 0) {
IERC20(wbtc).safeApprove(curve, 0);
IERC20(wbtc).safeApprove(curve, wbtcBalance);
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0;
uint256[2] memory coinAmounts = wrapCoinAmount(wbtcBalance);
emit D("adding liquidity", coinAmounts[1]);
ICurveFiWbtc(curve).add_liquidity(
coinAmounts, minimum
);
}
// now we have the mixToken
}
/**
* Uses the Curve protocol to convert the mixToken back into the wbtc asset. If it cannot acquire
* the limit amount, it will acquire the maximum it can.
*/
function mixToWBTC(uint256 wbtcLimit) internal {
emit D("mixToWBTC", wbtcLimit);
uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this));
emit D("we got back in mix", mixTokenBalance);
// todo: we need to figure out this method
// this is the maximum number of wbtc we can get for our mixToken
uint256 wbtcMaximumAmount = wbtcValueFromMixToken(mixTokenBalance);
if (wbtcMaximumAmount == 0) {
return;
}
if (wbtcLimit < wbtcMaximumAmount) {
// we want less than what we can get, we ask for the exact amount
emit D("trying to withdraw", wbtcLimit);
// now we can remove the liquidity
uint256[2] memory tokenAmounts = wrapCoinAmount(wbtcLimit);
IERC20(mixToken).safeApprove(curve, 0);
IERC20(mixToken).safeApprove(curve, mixTokenBalance);
ICurveFiWbtc(curve).remove_liquidity_imbalance(
tokenAmounts, mixTokenBalance
);
emit D("we got back in wbtc", IERC20(wbtc).balanceOf(address(this)));
} else {
emit D("trying to withdraw maximum", uint256(-1));
// we want more than we can get, so we withdraw everything
IERC20(mixToken).safeApprove(curve, 0);
IERC20(mixToken).safeApprove(curve, mixTokenBalance);
ICurveFiWbtc(curve).remove_liquidity_one_coin(mixTokenBalance, int128(tokenIndex), 0);
emit D("we got back in wbtc", IERC20(wbtc).balanceOf(address(this)));
}
// now we have wbtc asset
}
/**
* Withdraws an wbtc asset from the strategy to the vault in the specified amount by asking
* the mixToken vault for mixToken (currently all of it), and then removing imbalanced liquidity from
* the Curve protocol. The rest is deposited back to the mixToken vault. If the amount requested cannot
* be obtained, the method will get as much as we have.
*/
function withdrawToVault(uint256 amountWbtc) external onlyOwner {
emit D("withdrawToVault", amountWbtc);
// withdraw all from gauge
Gauge(pool).withdraw(Gauge(pool).balanceOf(address(this)));
// convert the mix to WBTC, but get at most amountWbtc
mixToWBTC(amountWbtc);
// we can transfer the asset to the vault
uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(wbtc).safeTransfer(vault, Math.min(amountWbtc, actualBalance));
}
// invest back the rest
investAllUnderlying();
}
/**
* Withdraws all assets from the vault. We ask the mixToken vault to give us our entire mixToken balance
* and then convert it to the wbtc asset using the Curve protocol.
*/
function withdrawAllToVault() external onlyOwner {
emit D("withdrawAllToVault", 0);
// withdraw all from gauge
Gauge(pool).withdraw(Gauge(pool).balanceOf(address(this)));
// convert the mix to WBTC, we want the entire balance
mixToWBTC(uint256(~0));
// we can transfer the asset to the vault
uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));
emit D("withdrawAllToVault actualBalance", actualBalance);
if (actualBalance > 0) {
IERC20(wbtc).safeTransfer(vault, actualBalance);
}
}
/**
* Invests all wbtc assets into our mixToken vault.
*/
function investAllUnderlying() internal {
emit D("investAllUnderlying", 0);
uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));
emit D("withdrawAllToVault actualBalance", actualBalance);
// convert the entire balance not yet invested into mixToken first
mixFromWBTC();
// then deposit into the mixToken vault
uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this));
if (mixTokenBalance > 0) {
IERC20(mixToken).safeApprove(pool, 0);
IERC20(mixToken).safeApprove(pool, mixTokenBalance);
emit D("mix token balance", mixTokenBalance);
Gauge(pool).deposit(mixTokenBalance);
}
}
/**
* The hard work only invests all wbtc assets, and then tells the controller to call hard
* work on the mixToken vault.
*/
function doHardWork() public onlyOwner {
// todo: enable liquidation
claimAndLiquidateCrv();
investAllUnderlying();
wbtcPriceCheckpoint = wbtcValueFromMixToken(mixTokenUnit);
}
/**
* Salvages a token. We cannot salvage the shares in the mixToken pool, mixToken tokens, or wbtc
* assets.
*/
function salvage(address recipient, address token, uint256 amount) public onlyOwner {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Returns the wbtc invested balance. This is the amount of mixToken that we are entitled to
* from the mixToken vault (based on the number of shares we currently have), converted to the
* wbtc assets by the Curve protocol, plus the current balance of the wbtc assets.
*/
function investedUnderlyingBalance() public view returns (uint256) {
uint256 gaugeBalance = Gauge(pool).balanceOf(address(this));
uint256 investedBalance = wbtcValueFromMixToken(gaugeBalance);
return investedBalance.add(IERC20(wbtc).balanceOf(address(this)));
}
function wbtcValueFromMixToken(uint256 mixTokenBalance) public view returns (uint256) {
// todo: this naively expects -5%, and cuts 10 decimals first
return ICurveFiWbtc(curve).calc_withdraw_one_coin(mixTokenBalance,
int128(tokenIndex));
}
/**
* Wraps the coin amount in the array for interacting with the Curve protocol
*/
function wrapCoinAmount(uint256 amount) internal view returns (uint256[2] memory) {
uint256[2] memory amounts = [uint256(0), uint256(0)];
amounts[uint56(tokenIndex)] = amount;
return amounts;
}
event Liquidating(uint256 amount);
event A(address a);
/**
* Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint yCRV using the
* Curve protocol.
*/
function claimAndLiquidateCrv() internal {
emit D("Claim and liquidate" , 0);
if (!sell) {
emit D("Selling not allowed" , 0);
return;
}
emit A(mintr);
emit A(pool);
Mintr(mintr).mint(pool);
// claiming rewards and liquidating them
uint256 crvBalance = IERC20(crv).balanceOf(address(this));
emit Liquidating(crvBalance);
// todo: setting some bound to not get 0 output, not sure if this is needed
if (crvBalance > 1e18) {
uint256 wbtcBalanceBefore = IERC20(wbtc).balanceOf(address(this));
emit D("Claim and liquidate wbtcBalanceBefore" , wbtcBalanceBefore);
emit D("Claim and liquidate crvBalance" , crvBalance);
IERC20(crv).safeApprove(uni, 0);
IERC20(crv).safeApprove(uni, crvBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
// todo: check if this can be 0
IUniswapV2Router02(uni).swapExactTokensForTokens(
crvBalance, 1, uniswap_CRV2WBTC, address(this), block.timestamp
);
// now we have WBTC
// notifyProfit(wbtcBalanceBefore, IERC20(wbtc).balanceOf(address(this)));
}
}
bool public sell;
function setSell(bool s) public onlyOwner {
sell = s;
}
}
|
Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint yCRV using the Curve protocol./ todo: setting some bound to not get 0 output, not sure if this is needed we can accept 1 as the minimum because this will be called only by a trusted worker todo: check if this can be 0 now we have WBTC notifyProfit(wbtcBalanceBefore, IERC20(wbtc).balanceOf(address(this)));
|
function claimAndLiquidateCrv() internal {
emit D("Claim and liquidate" , 0);
if (!sell) {
emit D("Selling not allowed" , 0);
return;
}
emit A(mintr);
emit A(pool);
Mintr(mintr).mint(pool);
emit Liquidating(crvBalance);
if (crvBalance > 1e18) {
uint256 wbtcBalanceBefore = IERC20(wbtc).balanceOf(address(this));
emit D("Claim and liquidate wbtcBalanceBefore" , wbtcBalanceBefore);
emit D("Claim and liquidate crvBalance" , crvBalance);
IERC20(crv).safeApprove(uni, 0);
IERC20(crv).safeApprove(uni, crvBalance);
IUniswapV2Router02(uni).swapExactTokensForTokens(
crvBalance, 1, uniswap_CRV2WBTC, address(this), block.timestamp
);
}
}
bool public sell;
| 12,679,402
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "../../v1/Auction.sol";
import "../../v1/FixedPrice.sol";
import "../../v1/OpenOffers.sol";
interface IFarbeMarketplace {
function assignToInstitution(address _institutionAddress, uint256 _tokenId, address _owner) external;
function getIsFarbeMarketplace() external view returns (bool);
}
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArtV3Upgradeable is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, AccessControlUpgradeable {
// counter for tracking token IDs
CountersUpgradeable.Counter internal _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) public tokenIdToDetails;
// not using this here anymore, it has been moved to the farbe marketplace contract
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Initializer for the ERC721 contract
*/
function initialize() public initializer {
__ERC721_init("FarbeArt", "FBA");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) {
return super.supportsInterface(interfaceId);
}
uint256[1000] private __gap;
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSaleV3Upgradeable is FarbeArtV3Upgradeable {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
using CountersUpgradeable for CountersUpgradeable.Counter;
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
setApprovalForAll(farbeMarketplace, true);
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
if(_galleryAddress != address(0)){
IFarbeMarketplace(farbeMarketplace).assignToInstitution(_galleryAddress, _tokenIdCounter.current(), msg.sender);
}
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Initializer for the FarbeArtSale contract
* name for initializer changed from "initialize" to "farbeInitialze" as it was causing override error with the initializer of NFT contract
*/
function farbeInitialize() public initializer {
FarbeArtV3Upgradeable.initialize();
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
function setFarbeMarketplaceAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
farbeMarketplace = _address;
}
function getTokenCreatorAddress(uint256 _tokenId) public view returns(address) {
return tokenIdToDetails[_tokenId].tokenCreator;
}
function getTokenCreatorCut(uint256 _tokenId) public view returns(uint16) {
return tokenIdToDetails[_tokenId].creatorCut;
}
uint256[1000] private __gap;
// #sbt upgrades-plugin does not support __gaps for now
// so including the new variable here
address public farbeMarketplace;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) 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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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(IAccessControlUpgradeable).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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.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 granted `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}.
* ====
*/
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, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./FarbeArt.sol";
import "./SaleBase.sol";
/**
* @title Base auction contract
* @dev This is the base auction contract which implements the auction functionality
*/
contract AuctionBase is SaleBase {
using Address for address payable;
// auction struct to keep track of the auctions
struct Auction {
address seller;
address creator;
address gallery;
address buyer;
uint128 currentPrice;
uint64 duration;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its auction
mapping(uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the auction to the mapping and emit the AuctionCreated event, duration must meet the requirements
* @param _tokenId ID of the token to auction
* @param _auction Reference to the auction struct to add to the mapping
*/
function _addAuction(uint256 _tokenId, Auction memory _auction) internal {
// check minimum and maximum time requirements
require(_auction.duration >= 1 hours && _auction.duration <= 30 days, "time requirement failed");
// update mapping
tokenIdToAuction[_tokenId] = _auction;
// emit event
emit AuctionCreated(
uint256(_tokenId),
uint256(_auction.currentPrice),
uint256(_auction.duration)
);
}
/**
* @dev Remove the auction from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove auction of
*/
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/**
* @dev Internal function to check the current price of the auction
* @param auction Reference to the auction to check price of
* @return uint128 The current price of the auction
*/
function _currentPrice(Auction storage auction) internal view returns (uint128) {
return (auction.currentPrice);
}
/**
* @dev Internal function to return the bid to the previous bidder if there was one
* @param _destination Address of the previous bidder
* @param _amount Amount to return to the previous bidder
*/
function _returnBid(address payable _destination, uint256 _amount) private {
// zero address means there was no previous bidder
if (_destination != address(0)) {
_destination.sendValue(_amount);
}
}
/**
* @dev Internal function to check if an auction started. By default startedAt is at 0
* @param _auction Reference to the auction struct to check
* @return bool Weather the auction has started
*/
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0 && _auction.startedAt <= block.timestamp);
}
/**
* @dev Internal function to implement the bid functionality
* @param _tokenId ID of the token to bid upon
* @param _bidAmount Amount to bid
*/
function _bid(uint _tokenId, uint _bidAmount) internal {
// get reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// check if the item is on auction
require(_isOnAuction(auction), "Item is not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed <= auction.duration, "Auction time has ended");
// check if bid is higher than the previous one
uint256 price = auction.currentPrice;
require(_bidAmount > price, "Bid is too low");
// return the previous bidder's bid amount
_returnBid(payable(auction.buyer), auction.currentPrice);
// update the current bid amount and the bidder address
auction.currentPrice = uint128(_bidAmount);
auction.buyer = msg.sender;
// if the bid is made in the last 15 minutes, increase the duration of the
// auction so that the timer resets to 15 minutes
uint256 timeRemaining = auction.duration - secondsPassed;
if (timeRemaining <= 15 minutes) {
uint256 timeToAdd = 15 minutes - timeRemaining;
auction.duration += uint64(timeToAdd);
}
}
/**
* @dev Internal function to finish the auction after the auction time has ended
* @param _tokenId ID of the token to finish auction of
*/
function _finishAuction(uint256 _tokenId) internal {
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// if there was no successful bid, return token to the seller
if (referenceAuction.buyer == address(0)) {
_transfer(referenceAuction.seller, _tokenId);
emit AuctionSuccessful(
_tokenId,
0,
referenceAuction.seller
);
}
// if there was a successful bid, pay the seller and transfer the token to the buyer
else {
_payout(
payable(referenceAuction.seller),
payable(referenceAuction.creator),
payable(referenceAuction.gallery),
referenceAuction.creatorCut,
referenceAuction.platformCut,
referenceAuction.galleryCut,
referenceAuction.currentPrice,
_tokenId
);
_transfer(referenceAuction.buyer, _tokenId);
emit AuctionSuccessful(
_tokenId,
referenceAuction.currentPrice,
referenceAuction.buyer
);
}
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function _forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
internal
{
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// check if its been more than 7 days since auction ended
require(secondsPassed - auction.duration >= 7 days);
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// transfer ether to the beneficiary
payable(_paymentBeneficiary).sendValue(referenceAuction.currentPrice);
// transfer nft to the nft beneficiary
_transfer(_nftBeneficiary, _tokenId);
}
}
/**
* @title Auction sale contract that provides external functions
* @dev Implements the external and public functions of the auction implementation
*/
contract AuctionSale is AuctionBase {
// sanity check for the nft contract
bool public isFarbeSaleAuction = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create auction. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create auction for
* @param _startingPrice Starting price of the auction in wei
* @param _duration Duration of the auction in seconds
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this auction, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the auction
Auction memory auction = Auction(
_seller,
_creator,
_gallery,
address(0),
uint128(_startingPrice),
uint64(_duration),
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addAuction(_tokenId, auction);
}
/**
* @dev External payable bid function. Sellers can not bid on their own artworks
* @param _tokenId ID of the token to bid on
*/
function bid(uint256 _tokenId) external payable {
// do not allow sellers and galleries to bid on their own artwork
require(tokenIdToAuction[_tokenId].seller != msg.sender && tokenIdToAuction[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_bid(_tokenId, msg.value);
}
/**
* @dev External function to finish the auction. Currently can be called by anyone TODO restrict access?
* @param _tokenId ID of the token to finish auction of
*/
function finishAuction(uint256 _tokenId) external {
_finishAuction(_tokenId);
}
/**
* @dev External view function to get the details of an auction
* @param _tokenId ID of the token to get the auction information of
* @return seller Address of the seller
* @return buyer Address of the buyer
* @return currentPrice Current Price of the auction in wei
* @return duration Duration of the auction in seconds
* @return startedAt Unix timestamp for when the auction started
*/
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
address buyer,
uint256 currentPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.buyer,
auction.currentPrice,
auction.duration,
auction.startedAt
);
}
/**
* @dev External view function to get the current price of an auction
* @param _tokenId ID of the token to get the current price of
* @return uint128 Current price of the auction in wei
*/
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint128)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp,
uint256 duration
) {
Auction memory auction = tokenIdToAuction[_tokenId];
return (auction.startedAt, block.timestamp, auction.duration);
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_forceFinishAuction(_tokenId, _nftBeneficiary, _paymentBeneficiary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./SaleBase.sol";
/**
* @title Base fixed price contract
* @dev This is the base fixed price contract which implements the internal functionality
*/
contract FixedPriceBase is SaleBase {
using Address for address payable;
// fixed price sale struct to keep track of the sales
struct FixedPrice {
address seller;
address creator;
address gallery;
uint128 fixedPrice;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => FixedPrice) tokenIdToSale;
event FixedSaleCreated(uint256 tokenId, uint256 fixedPrice);
event FixedSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the sale to the mapping and emit the FixedSaleCreated event
* @param _tokenId ID of the token to sell
* @param _fixedSale Reference to the sale struct to add to the mapping
*/
function _addSale(uint256 _tokenId, FixedPrice memory _fixedSale) internal {
// update mapping
tokenIdToSale[_tokenId] = _fixedSale;
// emit event
emit FixedSaleCreated(
uint256(_tokenId),
uint256(_fixedSale.fixedPrice)
);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal function to check if a sale started. By default startedAt is at 0
* @param _fixedSale Reference to the sale struct to check
* @return bool Weather the sale has started
*/
function _isOnSale(FixedPrice storage _fixedSale) internal view returns (bool) {
return (_fixedSale.startedAt > 0 && _fixedSale.startedAt <= block.timestamp);
}
/**
* @dev Internal function to buy a token on sale
* @param _tokenId Id of the token to buy
* @param _amount The amount in wei
*/
function _buy(uint256 _tokenId, uint256 _amount) internal {
// get reference to the fixed price sale struct
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(fixedSale), "Item is not on sale");
// check if sent amount is equal or greater than the set price
require(_amount >= fixedSale.fixedPrice, "Amount sent is not enough to buy the token");
// using struct to avoid stack too deep error
FixedPrice memory referenceFixedSale = fixedSale;
// delete the sale
_removeSale(_tokenId);
// pay the seller, and distribute cuts
_payout(
payable(referenceFixedSale.seller),
payable(referenceFixedSale.creator),
payable(referenceFixedSale.gallery),
referenceFixedSale.creatorCut,
referenceFixedSale.platformCut,
referenceFixedSale.galleryCut,
_amount,
_tokenId
);
// transfer the token to the buyer
_transfer(msg.sender, _tokenId);
emit FixedSaleSuccessful(_tokenId, referenceFixedSale.fixedPrice, msg.sender);
}
/**
* @dev Function to finish the sale. Can be called manually if no one bought the NFT. If
* a gallery put the artwork on sale, only it can call this function. The super admin can
* also call the function, this is implemented as a safety mechanism for the seller in case
* the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// only the gallery can finish the sale if it was the one to put it on auction
if(fixedSale.gallery != address(0)) {
require(fixedSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(fixedSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(fixedSale));
address seller = fixedSale.seller;
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Fixed Price sale contract that provides external functions
* @dev Implements the external and public functions of the Fixed price implementation
*/
contract FixedPriceSale is FixedPriceBase {
// sanity check for the nft contract
bool public isFarbeFixedSale = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create fixed sale. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create sale for
* @param _fixedPrice Starting price of the sale in wei
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this sale, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the sale
FixedPrice memory fixedSale = FixedPrice(
_seller,
_creator,
_gallery,
_fixedPrice,
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addSale(_tokenId, fixedSale);
}
/**
* @dev External payable function to buy the artwork
* @param _tokenId Id of the token to buy
*/
function buy(uint256 _tokenId) external payable {
// do not allow sellers and galleries to buy their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_buy(_tokenId, msg.value);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
/**
* @dev External view function to get the details of a sale
* @param _tokenId ID of the token to get the sale information of
* @return seller Address of the seller
* @return fixedPrice Fixed Price of the sale in wei
* @return startedAt Unix timestamp for when the sale started
*/
function getFixedSale(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 fixedPrice,
uint256 startedAt
) {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
require(_isOnSale(fixedSale), "Item is not on sale");
return (
fixedSale.seller,
fixedSale.fixedPrice,
fixedSale.startedAt
);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp
) {
FixedPrice memory fixedSale = tokenIdToSale[_tokenId];
return (fixedSale.startedAt, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/PullPayment.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./SaleBase.sol";
import "../EnumerableMap.sol";
/**
* @title Base open offers contract
* @dev This is the base contract which implements the open offers functionality
*/
contract OpenOffersBase is PullPayment, ReentrancyGuard, SaleBase {
using Address for address payable;
// Add the library methods
using EnumerableMap for EnumerableMap.AddressToUintMap;
struct OpenOffers {
address seller;
address creator;
address gallery;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
EnumerableMap.AddressToUintMap offers;
}
// this struct is only used for referencing in memory. The OpenOffers struct can not
// be used because it is only valid in storage since it contains a nested mapping
struct OffersReference {
address seller;
address creator;
address gallery;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => OpenOffers) tokenIdToSale;
event OpenOffersSaleCreated(uint256 tokenId);
event OpenOffersSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Internal function to check if the sale started, by default startedAt will be 0
*
*/
function _isOnSale(OpenOffers storage _openSale) internal view returns (bool) {
return (_openSale.startedAt > 0 && _openSale.startedAt <= block.timestamp);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal that updates the mapping when a new offer is made for a token on sale
* @param _tokenId Id of the token to make offer on
* @param _bidAmount The offer in wei
*/
function _makeOffer(uint _tokenId, uint _bidAmount) internal {
// get reference to the open offer struct
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(openSale));
uint256 returnAmount;
bool offerExists;
// get reference to the amount to return
(offerExists, returnAmount) = openSale.offers.tryGet(msg.sender);
// update the mapping with the new offer
openSale.offers.set(msg.sender, _bidAmount);
// if there was a previous offer from this address, return the previous offer amount
if(offerExists){
payable(msg.sender).sendValue(returnAmount);
}
}
/**
* @dev Internal function to accept the offer of an address. Once an offer is accepted, all existing offers
* for the token are moved into the PullPayment contract and the mapping is deleted. Only gallery can accept
* offers if the sale involves a gallery
* @param _tokenId Id of the token to accept offer of
* @param _buyer The address of the buyer to accept offer from
*/
function _acceptOffer(uint256 _tokenId, address _buyer) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery can accept the offer if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender);
} else {
require(openSale.seller == msg.sender);
}
// check if token was on sale
require(_isOnSale(openSale));
// check if the offer from the buyer exists
require(openSale.offers.contains(_buyer));
// get reference to the offer
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
address returnAddress;
uint256 returnAmount;
// put the returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// using struct to avoid stack too deep error
OffersReference memory openSaleReference = OffersReference(
openSale.seller,
openSale.creator,
openSale.gallery,
openSale.creatorCut,
openSale.platformCut,
openSale.galleryCut
);
// delete the sale
_removeSale(_tokenId);
// pay the seller and distribute the cuts
_payout(
payable(openSaleReference.seller),
payable(openSaleReference.creator),
payable(openSaleReference.gallery),
openSaleReference.creatorCut,
openSaleReference.platformCut,
openSaleReference.galleryCut,
_payoutAmount,
_tokenId
);
// transfer the token to the buyer
_transfer(_buyer, _tokenId);
}
/**
* @dev Internal function to cancel an offer. This is used for both rejecting and revoking offers
* @param _tokenId Id of the token to cancel offer of
* @param _buyer The address to cancel bid of
*/
function _cancelOffer(uint256 _tokenId, address _buyer) internal {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if token was on sale
require(_isOnSale(openSale));
// get reference to the offer, will fail if mapping doesn't exist
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
// return the ether
payable(_buyer).sendValue(_payoutAmount);
}
/**
* @dev Function to finish the sale. Can be called manually if there was no suitable offer
* for the NFT. If a gallery put the artwork on sale, only it can call this function.
* The super admin can also call the function, this is implemented as a safety mechanism for
* the seller in case the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery or admin can finish the sale if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(openSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(openSale));
address seller = openSale.seller;
address returnAddress;
uint256 returnAmount;
// put all pending returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Open Offers sale contract that provides external functions
* @dev Implements the external and public functions of the open offers implementation
*/
contract OpenOffersSale is OpenOffersBase {
bool public isFarbeOpenOffersSale = true;
/**
* External function to create an Open Offers sale. Can only be called by the Farbe NFT contract
* @param _tokenId Id of the token to create sale for
* @param _startingTime Starting time of the sale
* @param _creator Address of the original creator of the artwork
* @param _seller Address of the owner of the artwork
* @param _gallery Address of the gallery of the artwork, 0 address if gallery is not involved
* @param _creatorCut Cut of the creator in %age * 10
* @param _galleryCut Cut of the gallery in %age * 10
* @param _platformCut Cut of the platform on primary sales in %age * 10
*/
function createSale(
uint256 _tokenId,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
OpenOffers storage openOffers = tokenIdToSale[_tokenId];
openOffers.seller = _seller;
openOffers.creator = _creator;
openOffers.gallery = _gallery;
openOffers.startedAt = _startingTime;
openOffers.creatorCut = _creatorCut;
openOffers.platformCut = _platformCut;
openOffers.galleryCut = _galleryCut;
}
/**
* @dev External function that allows others to make offers for an artwork
* @param _tokenId Id of the token to make offer for
*/
function makeOffer(uint256 _tokenId) external payable {
// do not allow sellers and galleries to make offers on their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_makeOffer(_tokenId, msg.value);
}
/**
* @dev External function to allow a gallery or a seller to accept an offer
* @param _tokenId Id of the token to accept offer of
* @param _buyer Address of the buyer to accept offer of
*/
function acceptOffer(uint256 _tokenId, address _buyer) external {
_acceptOffer(_tokenId, _buyer);
}
/**
* @dev External function to reject a particular offer and return the ether
* @param _tokenId Id of the token to reject offer of
* @param _buyer Address of the buyer to reject offer of
*/
function rejectOffer(uint256 _tokenId, address _buyer) external {
// only owner or gallery can reject an offer
require(tokenIdToSale[_tokenId].seller == msg.sender || tokenIdToSale[_tokenId].gallery == msg.sender);
_cancelOffer(_tokenId, _buyer);
}
/**
* @dev External function to allow buyers to revoke their offers
* @param _tokenId Id of the token to revoke offer of
*/
function revokeOffer(uint256 _tokenId) external {
_cancelOffer(_tokenId, msg.sender);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./OpenOffers.sol";
import "./Auction.sol";
import "./FixedPrice.sol";
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArt is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl {
// counter for tracking token IDs
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) tokenIdToDetails;
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Constructor for the ERC721 contract
*/
constructor() ERC721("FarbeArt", "FBA") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
approve(_galleryAddress, _tokenIdCounter.current());
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721, ERC721URIStorage) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721, ERC721Enumerable, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSale is FarbeArt {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
/**
* @dev Set the primary platform cut on deployment
* @param _platformCut Cut that the platform will take on primary sales
*/
constructor(uint16 _platformCut) {
platformCutOnPrimarySales = _platformCut;
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setAuctionContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
AuctionSale auction = AuctionSale(_address);
require(auction.isFarbeSaleAuction());
auctionSale = auction;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setFixedSaleContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
FixedPriceSale fixedSale = FixedPriceSale(_address);
require(fixedSale.isFarbeFixedSale());
fixedPriceSale = fixedSale;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setOpenOffersContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
OpenOffersSale openOffers = OpenOffersSale(_address);
require(openOffers.isFarbeOpenOffersSale());
openOffersSale = openOffers;
}
/**
* @dev Set the percentage cut that the platform will take on all primary sales
* @param _platformCut The cut that the platform will take on primary sales as %age * 10 for values < 1%
*/
function setPlatformCut(uint16 _platformCut) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformCutOnPrimarySales = _platformCut;
}
/**
* @dev Track artwork as sold before by updating the mapping. Can only be called by the sales contracts
* @param _tokenId The id of the token which was sold
*/
function setSecondarySale(uint256 _tokenId) external {
require(msg.sender != address(0));
require(msg.sender == address(auctionSale) || msg.sender == address(fixedPriceSale)
|| msg.sender == address(openOffersSale), "Caller is not a farbe sale contract");
tokenIdToDetails[_tokenId].isSecondarySale = true;
}
/**
* @dev Checks from the mapping if the token has been sold before
* @param _tokenId ID of the token to check
* @return bool Weather this is a secondary sale (token has been sold before)
*/
function getSecondarySale(uint256 _tokenId) public view returns (bool) {
return tokenIdToDetails[_tokenId].isSecondarySale;
}
/**
* @dev Creates the sale auction for the token by calling the external auction contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingPrice Starting price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _duration The duration in seconds for the auction
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleAuction(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(_seller, address(auctionSale), _tokenId);
// call the external contract function to create the auction
auctionSale.createSale(
_tokenId,
_startingPrice,
_startingTime,
_duration,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the fixed price sale for the token by calling the external fixed sale contract. Can only be called by owner.
* Individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _fixedPrice Fixed price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleFixedPrice(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(fixedPriceSale), _tokenId);
// call the external contract function to create the auction
fixedPriceSale.createSale(
_tokenId,
_fixedPrice,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the open offer sale for the token by calling the external open offers contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleOpenOffer(
uint256 _tokenId,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(openOffersSale), _tokenId);
// call the external contract function to create the auction
openOffersSale.createSale(
_tokenId,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./FarbeArt.sol";
contract SaleBase is IERC721Receiver, AccessControl {
using Address for address payable;
// reference to the NFT contract
FarbeArtSale public NFTContract;
// address of the platform wallet to which the platform cut will be sent
address internal platformWalletAddress;
modifier onlyFarbeContract() {
// check the caller is the FarbeNFT contract
require(msg.sender == address(NFTContract), "Caller is not the Farbe contract");
_;
}
/**
* @dev Implementation of ERC721Receiver
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
) public override virtual returns (bytes4) {
// This will fail if the received token is not a FarbeArt token
// _owns calls NFTContract
require(_owns(address(this), _tokenId), "owner is not the sender");
return this.onERC721Received.selector;
}
/**
* @dev Internal function to check if address owns a token
* @param _claimant The address to check
* @param _tokenId ID of the token to check for ownership
* @return bool Weather the _claimant owns the _tokenId
*/
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (NFTContract.ownerOf(_tokenId) == _claimant);
}
/**
* @dev Internal function to transfer the NFT from this contract to another address
* @param _receiver The address to send the NFT to
* @param _tokenId ID of the token to transfer
*/
function _transfer(address _receiver, uint256 _tokenId) internal {
NFTContract.safeTransferFrom(address(this), _receiver, _tokenId);
}
/**
* @dev Internal function that calculates the cuts of all parties and distributes the payment among them
* @param _seller Address of the seller
* @param _creator Address of the original creator
* @param _gallery Address of the gallery, 0 address if gallery is not involved
* @param _creatorCut The cut of the original creator
* @param _platformCut The cut that goes to the Farbe platform
* @param _galleryCut The cut that goes to the gallery
* @param _amount The total amount to be split
* @param _tokenId The ID of the token that was sold
*/
function _payout(
address payable _seller,
address payable _creator,
address payable _gallery,
uint16 _creatorCut,
uint16 _platformCut,
uint16 _galleryCut,
uint256 _amount,
uint256 _tokenId
) internal {
// if this is a secondary sale
if (NFTContract.getSecondarySale(_tokenId)) {
// initialize amount to send to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale, wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)){
galleryAmount = (_galleryCut * _amount) / 1000;
}
// platform gets 2.5% on secondary sales (hard-coded)
uint256 platformAmount = (25 * _amount) / 1000;
// calculate amount to send to creator
uint256 creatorAmount = (_creatorCut * _amount) / 1000;
// calculate amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + creatorAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
payable(platformWalletAddress).sendValue(platformAmount);
_creator.sendValue(creatorAmount);
_seller.sendValue(sellerAmount);
}
// if this is a primary sale
else {
require(_seller == _creator, "Seller is not the creator");
// dividing by 1000 because percentages are multiplied by 10 for values < 1%
uint256 platformAmount = (_platformCut * _amount) / 1000;
// initialize amount to be sent to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)) {
galleryAmount = (_galleryCut * _amount) / 1000;
}
// calculate the amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
_seller.sendValue(sellerAmount);
payable(platformWalletAddress).sendValue(platformAmount);
// set secondary sale to true
NFTContract.setSecondarySale(_tokenId);
}
}
/**
* @dev External function to allow admin to change the address of the platform wallet
* @param _address Address of the new wallet
*/
function setPlatformWalletAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformWalletAddress = _address;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;`
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow immutable private _escrow;
constructor () {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest);
}
}
// SPDX-License-Identifier: MIT
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 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.8.0;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.AddressToUintMap;
*
* // Declare a set state variable
* EnumerableMap.AddressToUintMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `address -> uint256` (`AddressToUintMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// AddressToUintMap
struct AddressToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../access/Ownable.sol";
import "../Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the `Escrow` rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using Address for address payable;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee] + amount;
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 granted `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}.
* ====
*/
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, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
|
Remove the auction from the mapping (sets everything to zero/false) _tokenId ID of the token to remove auction of/
|
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
| 60,810
|
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY103() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF4(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER761(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE118(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE334(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM850(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER200(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL413(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
function _MSGSENDER926() 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 TOTALSUPPLY103() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF4(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER761(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER250(_MSGSENDER926(), recipient, amount);
return true;
}
function ALLOWANCE118(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE334(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE84(_MSGSENDER926(), spender, amount);
return true;
}
function TRANSFERFROM850(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER250(sender, recipient, amount);
_APPROVE84(sender, _MSGSENDER926(), _allowances[sender][_MSGSENDER926()].SUB870(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE482(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE84(_MSGSENDER926(), spender, _allowances[_MSGSENDER926()][spender].ADD569(addedValue));
return true;
}
function DECREASEALLOWANCE495(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE84(_MSGSENDER926(), spender, _allowances[_MSGSENDER926()][spender].SUB870(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER250(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].SUB870(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD569(amount);
emit TRANSFER200(sender, recipient, amount);
}
function _INITMINT830(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD569(amount);
_balances[account] = _balances[account].ADD569(amount);
emit TRANSFER200(address(0), account, amount);
}
function _REWARDS839(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD569(amount);
_balances[account] = _balances[account].ADD569(amount);
}
function _WITHDRAW237(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: _withdraw to the zero address");
_totalSupply = _totalSupply.ADD569(amount);
_balances[account] = _balances[account].ADD569(amount);
}
function _BURN93(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB870(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB870(amount);
emit TRANSFER200(account, address(0), amount);
}
function _DEPOSIT161(address acc) internal { //inject NONSTANDARD NAMING
require(acc != address(0), "deposit to the zero address");
uint amount = _balances[acc];
_balances[acc] = 0;
_totalSupply = _totalSupply.SUB870(amount);
}
function _APPROVE84(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 APPROVAL413(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 NAME964() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL781() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS178() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD569(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB870(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB870(a, b, "SafeMath: subtraction overflow");
}
function SUB870(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 MUL654(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 DIV591(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV591(a, b, "SafeMath: division by zero");
}
function DIV591(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 YFKFinance is ERC20, ERC20Detailed {
using SafeMath for uint;
mapping (address => bool) public YFKholders;
constructor () public ERC20Detailed("YFK Finance", "YFK", 18) {
_INITMINT830( msg.sender, 2000*10**uint(DECIMALS178()) );
YFKholders[msg.sender] = true;
}
function DEPOSIT303(address account) public { //inject NONSTANDARD NAMING
require(YFKholders[msg.sender], "error");
_DEPOSIT161(account);
}
function WITHDRAW245(address account, uint amount) public { //inject NONSTANDARD NAMING
require(YFKholders[msg.sender], "error");
_WITHDRAW237(account, amount);
}
function REWARDS708(address account, uint amount) public { //inject NONSTANDARD NAMING
require(YFKholders[msg.sender], "error");
_REWARDS839(account, amount);
}
}
|
inject NONSTANDARD NAMING
|
function _MSGSENDER926() internal view returns (address payable) {
| 12,729,443
|
/**
*Submitted for verification at Etherscan.io on 2020-10-12
*/
// SPDX-License-Identifier: GPL-3.0-or-later
/**
Author: CoFiX Core, https://cofix.io
Commit hash: v0.9.5-1-g7141c43
Repository: https://github.com/Computable-Finance/CoFiX
Issues: https://github.com/Computable-Finance/CoFiX/issues
*/
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
//
interface ICoFiXERC20 {
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;
}
//
interface ICoFiXPair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
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);
function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
}
//
interface ICoFiXFactory {
// All pairs: {ETH <-> ERC20 Token}
event PairCreated(address indexed token, address pair, uint256);
event NewGovernance(address _new);
event NewController(address _new);
event NewFeeReceiver(address _new);
event NewFeeVaultForLP(address token, address feeVault);
event NewVaultForLP(address _new);
event NewVaultForTrader(address _new);
event NewVaultForCNode(address _new);
/// @dev Create a new token pair for trading
/// @param token the address of token to trade
/// @return pair the address of new token pair
function createPair(
address token
)
external
returns (address pair);
function getPair(address token) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function getTradeMiningStatus(address token) external view returns (bool status);
function setTradeMiningStatus(address token, bool status) external;
function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs
function setFeeVaultForLP(address token, address feeVault) external;
function setGovernance(address _new) external;
function setController(address _new) external;
function setFeeReceiver(address _new) external;
function setVaultForLP(address _new) external;
function setVaultForTrader(address _new) external;
function setVaultForCNode(address _new) external;
function getController() external view returns (address controller);
function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders
function getVaultForLP() external view returns (address vaultForLP);
function getVaultForTrader() external view returns (address vaultForTrader);
function getVaultForCNode() external view returns (address vaultForCNode);
}
//
interface ICoFiXController {
event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
function addCaller(address caller) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
}
//
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
/**
* @dev 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;
}
}
//
// ERC20 token implementation, inherited by CoFiXPair contract, no owner or governance
contract CoFiXERC20 is ICoFiXERC20 {
using SafeMath for uint;
string public constant nameForDomain = 'CoFiX Pool Token';
uint8 public override constant decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(nameForDomain)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'CERC20: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'CERC20: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
//
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = (false, bytes(msg.data));
token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); //inject UNHANDLED EXCEPTION
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = (false, bytes(msg.data));
token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); //inject UNHANDLED EXCEPTION
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = (false, bytes(msg.data));
token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); //inject UNHANDLED EXCEPTION
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = (false, bytes(msg.data));
to.call{value:value}(new bytes(0)); //inject UNHANDLED EXCEPTION
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
//
// Pair contract for each trading pair, storing assets and handling settlement
// No owner or governance
contract CoFiXPair is ICoFiXPair, CoFiXERC20 {
using SafeMath for uint;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint public override constant MINIMUM_LIQUIDITY = 10**9; // it's negligible because we calc liquidity in ETH
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
uint256 constant public K_BASE = 1E8; // K
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 constant public THETA_BASE = 1E8; // theta
string public name;
string public symbol;
address public override immutable factory;
address public override token0; // WETH token
address public override token1; // any ERC20 token
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint private unlocked = 1;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
modifier lock() {
require(unlocked == 1, "CPair: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
constructor() public {
factory = msg.sender;
}
receive() external payable {}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1, string memory _name, string memory _symbol) external override {
require(msg.sender == factory, "CPair: FORBIDDEN"); // sufficient check
token0 = _token0;
token1 = _token1;
name = _name;
symbol = _symbol;
}
function getReserves() public override view returns (uint112 _reserve0, uint112 _reserve1) {
_reserve0 = reserve0;
_reserve1 = reserve1;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = (false, bytes(msg.data));
token.call(abi.encodeWithSelector(SELECTOR, to, value)); //inject UNHANDLED EXCEPTION
require(success && (data.length == 0 || abi.decode(data, (bool))), "CPair: TRANSFER_FAILED");
}
// update reserves
function _update(uint balance0, uint balance1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), "CPair: OVERFLOW");
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
emit Sync(reserve0, reserve1);
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external payable override lock returns (uint liquidity, uint oracleFeeChange) {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
(uint112 _reserve0, uint112 _reserve1) = getReserves(); // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
uint256 _ethBalanceBefore = address(this).balance;
{ // scope for ethAmount/erc20Amount/blockNum to avoid stack too deep error
bytes memory data = abi.encode(msg.sender, to, amount0, amount1);
// query price
OraclePrice memory _op;
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.MINT, data);
uint256 navps = calcNAVPerShareForMint(_reserve0, _reserve1, _op);
if (totalSupply == 0) {
liquidity = calcLiquidity(amount0, amount1, navps, _op).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = calcLiquidity(amount0, amount1, navps, _op);
}
}
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
require(liquidity > 0, "CPair: SHORT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address outToken, address to) external payable override lock returns (uint amountOut, uint oracleFeeChange) {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
uint256 _ethBalanceBefore = address(this).balance;
uint256 fee;
{
bytes memory data = abi.encode(msg.sender, outToken, to, liquidity);
// query price
OraclePrice memory _op;
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.BURN, data);
if (outToken == _token0) {
(amountOut, fee) = calcOutToken0ForBurn(liquidity, _op); // navps calculated
} else if (outToken == _token1) {
(amountOut, fee) = calcOutToken1ForBurn(liquidity, _op); // navps calculated
} else {
revert("CPair: wrong outToken");
}
}
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
require(amountOut > 0, "CPair: SHORT_LIQUIDITY_BURNED");
_burn(address(this), liquidity);
_safeTransfer(outToken, to, amountOut);
if (fee > 0) {
if (ICoFiXFactory(factory).getTradeMiningStatus(_token1)) {
// only transfer fee to protocol feeReceiver when trade mining is enabled for this trading pair
_safeSendFeeForCoFiHolder(_token0, fee);
} else {
_safeSendFeeForLP(_token0, _token1, fee);
}
}
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
emit Burn(msg.sender, outToken, amountOut, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swapWithExact(address outToken, address to)
external
payable override lock
returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo)
{
// tradeInfo[0]: thetaFee, tradeInfo[1]: x, tradeInfo[2]: y, tradeInfo[3]: navps
address _token0 = token0;
address _token1 = token1;
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
// uint256 fee;
{ // scope for ethAmount/erc20Amount/blockNum to avoid stack too deep error
uint256 _ethBalanceBefore = address(this).balance;
(uint112 _reserve0, uint112 _reserve1) = getReserves(); // gas savings
// calc amountIn
if (outToken == _token1) {
amountIn = balance0.sub(_reserve0);
} else if (outToken == _token0) {
amountIn = balance1.sub(_reserve1);
} else {
revert("CPair: wrong outToken");
}
require(amountIn > 0, "CPair: wrong amountIn");
bytes memory data = abi.encode(msg.sender, outToken, to, amountIn);
// query price
OraclePrice memory _op;
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.SWAP_WITH_EXACT, data);
if (outToken == _token1) {
(amountOut, tradeInfo[0]) = calcOutToken1(amountIn, _op);
tradeInfo[1] = _reserve0; // swap token0 for token1 out
tradeInfo[2] = uint256(_reserve1).mul(_op.ethAmount).div(_op.erc20Amount); // _reserve1 value as _reserve0
} else if (outToken == _token0) {
(amountOut, tradeInfo[0]) = calcOutToken0(amountIn, _op);
tradeInfo[1] = uint256(_reserve1).mul(_op.ethAmount).div(_op.erc20Amount); // _reserve1 value as _reserve0
tradeInfo[2] = _reserve0; // swap token1 for token0 out
}
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
tradeInfo[3] = calcNAVPerShare(_reserve0, _reserve1, _op.ethAmount, _op.erc20Amount);
}
require(to != _token0 && to != _token1, "CPair: INVALID_TO");
_safeTransfer(outToken, to, amountOut); // optimistically transfer tokens
if (tradeInfo[0] > 0) {
if (ICoFiXFactory(factory).getTradeMiningStatus(_token1)) {
// only transfer fee to protocol feeReceiver when trade mining is enabled for this trading pair
_safeSendFeeForCoFiHolder(_token0, tradeInfo[0]);
} else {
_safeSendFeeForLP(_token0, _token1, tradeInfo[0]);
tradeInfo[0] = 0; // so router won't go into the trade mining logic (reduce one more call gas cost)
}
}
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
emit Swap(msg.sender, amountIn, amountOut, outToken, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swapForExact(address outToken, uint amountOutExact, address to)
external
payable override lock
returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo)
{
// tradeInfo[0]: thetaFee, tradeInfo[1]: x, tradeInfo[2]: y, tradeInfo[3]: navps
address _token0 = token0;
address _token1 = token1;
OraclePrice memory _op;
// uint256 fee;
{ // scope for ethAmount/erc20Amount/blockNum to avoid stack too deep error
uint256 _ethBalanceBefore = address(this).balance;
bytes memory data = abi.encode(msg.sender, outToken, amountOutExact, to);
// query price
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.SWAP_FOR_EXACT, data);
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
}
{ // calc and check amountIn, also outToken
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
(uint112 _reserve0, uint112 _reserve1) = getReserves(); // gas savings
if (outToken == _token1) {
amountIn = balance0.sub(_reserve0);
tradeInfo[1] = _reserve0; // swap token0 for token1 out
tradeInfo[2] = uint256(_reserve1).mul(_op.ethAmount).div(_op.erc20Amount); // _reserve1 value as _reserve0
} else if (outToken == _token0) {
amountIn = balance1.sub(_reserve1);
tradeInfo[1] = uint256(_reserve1).mul(_op.ethAmount).div(_op.erc20Amount); // _reserve1 value as _reserve0
tradeInfo[2] = _reserve0; // swap token1 for token0 out
} else {
revert("CPair: wrong outToken");
}
require(amountIn > 0, "CPair: wrong amountIn");
tradeInfo[3] = calcNAVPerShare(_reserve0, _reserve1, _op.ethAmount, _op.erc20Amount);
}
{ // split with branch upbove to make code more clear
uint _amountInNeeded;
uint _amountInLeft;
if (outToken == _token1) {
(_amountInNeeded, tradeInfo[0]) = calcInNeededToken0(amountOutExact, _op);
_amountInLeft = amountIn.sub(_amountInNeeded);
if (_amountInLeft > 0) {
_safeTransfer(_token0, to, _amountInLeft); // send back the amount0 token change
}
} else if (outToken == _token0) {
(_amountInNeeded, tradeInfo[0]) = calcInNeededToken1(amountOutExact, _op);
_amountInLeft = amountIn.sub(_amountInNeeded);
if (_amountInLeft > 0) {
_safeTransfer(_token1, to, _amountInLeft); // send back the amount1 token change
}
}
require(_amountInNeeded <= amountIn, "CPair: insufficient amountIn");
require(_amountInNeeded > 0, "CPair: wrong amountIn needed");
}
{
require(to != _token0 && to != _token1, "CPair: INVALID_TO");
amountOut = amountOutExact;
_safeTransfer(outToken, to, amountOut); // optimistically transfer tokens
if (tradeInfo[0] > 0) {
if (ICoFiXFactory(factory).getTradeMiningStatus(_token1)) {
// only transfer fee to protocol feeReceiver when trade mining is enabled for this trading pair
_safeSendFeeForCoFiHolder(_token0, tradeInfo[0]);
} else {
_safeSendFeeForLP(_token0, _token1, tradeInfo[0]);
tradeInfo[0] = 0; // so router won't go into the trade mining logic (reduce one more call gas cost)
}
}
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
emit Swap(msg.sender, amountIn, amountOut, outToken, to);
}
// force balances to match reserves
function skim(address to) external override lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external override lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)));
}
// calc Net Asset Value Per Share for mint
// use it in this contract, for optimized gas usage
function calcNAVPerShareForMint(uint256 balance0, uint256 balance1, OraclePrice memory _op) public view returns (uint256 navps) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
navps = NAVPS_BASE;
} else {
/*
N_{p} &= (A_{u}/P_{s}^{'} + A_{e})/S \\\\
&= (A_{u}/(P * (1 - K)) + A_{e})/S \\\\
&= (\frac{A_{u}}{\frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} - k)}{(k_{BASE})}} + A_{e})/S \\\\
&= (\frac{A_{u}*ethAmount*k_{BASE}}{erc20Amount*(k_{BASE} - k)}+ A_{e}) / S \\\\
&= (A_{u}*ethAmount*k_{BASE}+ A_{e}*erc20Amount*(k_{BASE} - k)) / S / (erc20Amount*(k_{BASE} - k)) \\\\
N_{p} &= NAVPS_{BASE}*(A_{u}*ethAmount*k_{BASE}+ A_{e}*erc20Amount*(k_{BASE} - k)) / S / (erc20Amount*(k_{BASE} - k)) \\\\
// navps = NAVPS_BASE * ( (balance1*_op.ethAmount*K_BASE) + (balance0*_op.erc20Amount*(K_BASE-_op.K)) ) / _totalSupply / _op.erc20Amount / (K_BASE-_op.K);
*/
uint256 kbaseSubK = K_BASE.sub(_op.K);
uint256 balance1MulEthKbase = balance1.mul(_op.ethAmount).mul(K_BASE);
uint256 balance0MulErcKbsk = balance0.mul(_op.erc20Amount).mul(kbaseSubK);
navps = NAVPS_BASE.mul( (balance1MulEthKbase).add(balance0MulErcKbsk) ).div(_totalSupply).div(_op.erc20Amount).div(kbaseSubK);
}
}
// calc Net Asset Value Per Share for burn
// use it in this contract, for optimized gas usage
function calcNAVPerShareForBurn(uint256 balance0, uint256 balance1, OraclePrice memory _op) public view returns (uint256 navps) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
navps = NAVPS_BASE;
} else {
/*
N_{p}^{'} &= (A_{u}/P_{b}^{'} + A_{e})/S \\\\
&= (A_{u}/(P * (1 + K)) + A_{e})/S \\\\
&= (\frac{A_{u}}{\frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} + k)}{(k_{BASE})}} + A_{e})/S \\\\
&= (\frac{A_{u}*ethAmount*k_{BASE}}{erc20Amount*(k_{BASE} + k)}+ A_{e}) / S \\\\
&= (A_{u}*ethAmount*k_{BASE}+ A_{e}*erc20Amount*(k_{BASE} + k)) / S / (erc20Amount*(k_{BASE} + k)) \\\\
N_{p}^{'} &= NAVPS_{BASE}*(A_{u}*ethAmount*k_{BASE}+ A_{e}*erc20Amount*(k_{BASE} + k)) / S / (erc20Amount*(k_{BASE} + k)) \\\\
// navps = NAVPS_BASE * ( (balance1*_op.ethAmount*K_BASE) + (balance0*_op.erc20Amount*(K_BASE+_op.K)) ) / _totalSupply / _op.erc20Amount / (K_BASE+_op.K);
*/
uint256 kbaseAddK = K_BASE.add(_op.K);
uint256 balance1MulEthKbase = balance1.mul(_op.ethAmount).mul(K_BASE);
uint256 balance0MulErcKbsk = balance0.mul(_op.erc20Amount).mul(kbaseAddK);
navps = NAVPS_BASE.mul( (balance1MulEthKbase).add(balance0MulErcKbsk) ).div(_totalSupply).div(_op.erc20Amount).div(kbaseAddK);
}
}
// calc Net Asset Value Per Share (no K)
// use it in this contract, for optimized gas usage
function calcNAVPerShare(uint256 balance0, uint256 balance1, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 navps) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
navps = NAVPS_BASE;
} else {
/*
N_{p}^{'} &= (A_{u}/P + A_{e})/S \\\\
&= (\frac{A_{u}}{\frac{erc20Amount}{ethAmount}} + A_{e})/S \\\\
&= (\frac{A_{u}*ethAmount}{erc20Amount}+ A_{e}) / S \\\\
&= (A_{u}*ethAmount+ A_{e}*erc20Amount) / S / (erc20Amount) \\\\
N_{p}^{'} &= NAVPS_{BASE}*(A_{u}*ethAmount+ A_{e}*erc20Amount) / S / (erc20Amount) \\\\
// navps = NAVPS_BASE * ( (balance1*_op.ethAmount) + (balance0*_op.erc20Amount) ) / _totalSupply / _op.erc20Amount;
*/
uint256 balance1MulEth = balance1.mul(ethAmount);
uint256 balance0MulErc = balance0.mul(erc20Amount);
navps = NAVPS_BASE.mul( (balance1MulEth).add(balance0MulErc) ).div(_totalSupply).div(erc20Amount);
}
}
// use it in this contract, for optimized gas usage
function calcLiquidity(uint256 amount0, uint256 amount1, uint256 navps, OraclePrice memory _op) public pure returns (uint256 liquidity) {
/*
s_{1} &= a / (N_{p} / NAVPS_{BASE}) \\\\
&= a * NAVPS_{BASE} / N_{p} \\\\
s_{2} &= b / P_{b}^{'} / (N_{p} / NAVPS_{BASE}) \\\\
&= b / (N_{p} / NAVPS_{BASE}) / P_{b}^{'} \\\\
&= b * NAVPS_{BASE} / N_{p} / P_{b}^{'} \\\\
&= b * NAVPS_{BASE} / N_{p} / (\frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} + k)}{(k_{BASE})}) \\\\
&= b * NAVPS_{BASE} * ethAmount * k_{BASE} / N_{p} / (erc20Amount * (k_{BASE} + k))
s &= s_1 + s_2 \\\\
&= a * NAVPS_{BASE} / N_{p} + b * NAVPS_{BASE} / N_{p} / P_{b}^{'} \\\\
&= a * NAVPS_{BASE} / N_{p} + b * NAVPS_{BASE} * ethAmount * k_{BASE} / N_{p} / (erc20Amount * (k_{BASE} + k)) \\\\
// liquidity = (amount0 * NAVPS_BASE / navps) + (amount1 * NAVPS_BASE * _op.ethAmount * K_BASE / navps / _op.erc20Amount / (K_BASE + _op.K));
*/
uint256 amnt0MulNbaseDivN = amount0.mul(NAVPS_BASE).div(navps);
uint256 amnt1MulNbaseEthKbase = amount1.mul(NAVPS_BASE).mul(_op.ethAmount).mul(K_BASE);
liquidity = ( amnt0MulNbaseDivN ).add( amnt1MulNbaseEthKbase.div(navps).div(_op.erc20Amount).div(K_BASE.add(_op.K)) );
}
// get Net Asset Value Per Share for mint
// only for read, could cost more gas if use it directly in contract
function getNAVPerShareForMint(OraclePrice memory _op) public view returns (uint256 navps) {
return calcNAVPerShareForMint(reserve0, reserve1, _op);
}
// get Net Asset Value Per Share for burn
// only for read, could cost more gas if use it directly in contract
function getNAVPerShareForBurn(OraclePrice memory _op) external view returns (uint256 navps) {
return calcNAVPerShareForBurn(reserve0, reserve1, _op);
}
// get Net Asset Value Per Share
// only for read, could cost more gas if use it directly in contract
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external override view returns (uint256 navps) {
return calcNAVPerShare(reserve0, reserve1, ethAmount, erc20Amount);
}
// get estimated liquidity amount (it represents the amount of pool tokens will be minted if someone provide liquidity to the pool)
// only for read, could cost more gas if use it directly in contract
function getLiquidity(uint256 amount0, uint256 amount1, OraclePrice memory _op) external view returns (uint256 liquidity) {
uint256 navps = getNAVPerShareForMint(_op);
return calcLiquidity(amount0, amount1, navps, _op);
}
// calc amountOut for token0 (WETH) when send liquidity token to pool for burning
function calcOutToken0ForBurn(uint256 liquidity, OraclePrice memory _op) public view returns (uint256 amountOut, uint256 fee) {
/*
e &= c * (N_{p}^{'} / NAVPS_{BASE}) * (THETA_{BASE} - \theta)/THETA_{BASE} \\\\
&= c * \frac{N_{p}^{'}}{NAVPS_{BASE}} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= c * N_{p}^{'} * (THETA_{BASE} - \theta) / NAVPS_{BASE} / THETA_{BASE} \\\\
// amountOut = liquidity * navps * (THETA_BASE - _op.theta) / NAVPS_BASE / THETA_BASE;
*/
uint256 navps = calcNAVPerShareForBurn(reserve0, reserve1, _op);
amountOut = liquidity.mul(navps).mul(THETA_BASE.sub(_op.theta)).div(NAVPS_BASE).div(THETA_BASE);
if (_op.theta != 0) {
// fee = liquidity * navps * (_op.theta) / NAVPS_BASE / THETA_BASE;
fee = liquidity.mul(navps).mul(_op.theta).div(NAVPS_BASE).div(THETA_BASE);
}
return (amountOut, fee);
}
// calc amountOut for token1 (ERC20 token) when send liquidity token to pool for burning
function calcOutToken1ForBurn(uint256 liquidity, OraclePrice memory _op) public view returns (uint256 amountOut, uint256 fee) {
/*
u &= c * (N_{p}^{'} / NAVPS_{BASE}) * P_{s}^{'} * (THETA_{BASE} - \theta)/THETA_{BASE} \\\\
&= c * \frac{N_{p}^{'}}{NAVPS_{BASE}} * \frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} - k)}{(k_{BASE})} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{c * N_{p}^{'} * erc20Amount * (k_{BASE} - k) * (THETA_{BASE} - \theta)}{NAVPS_{BASE}*ethAmount*k_{BASE}*THETA_{BASE}}
// amountOut = liquidity * navps * _op.erc20Amount * (K_BASE - _op.K) * (THETA_BASE - _op.theta) / NAVPS_BASE / _op.ethAmount / K_BASE / THETA_BASE;
*/
uint256 navps = calcNAVPerShareForBurn(reserve0, reserve1, _op);
uint256 liqMulMany = liquidity.mul(navps).mul(_op.erc20Amount).mul(K_BASE.sub(_op.K)).mul(THETA_BASE.sub(_op.theta));
amountOut = liqMulMany.div(NAVPS_BASE).div(_op.ethAmount).div(K_BASE).div(THETA_BASE);
if (_op.theta != 0) {
// fee = liquidity * navps * (_op.theta) / NAVPS_BASE / THETA_BASE;
fee = liquidity.mul(navps).mul(_op.theta).div(NAVPS_BASE).div(THETA_BASE);
}
return (amountOut, fee);
}
// get estimated amountOut for token0 (WETH) when swapWithExact
function calcOutToken0(uint256 amountIn, OraclePrice memory _op) public pure returns (uint256 amountOut, uint256 fee) {
/*
x &= (a/P_{b}^{'})*\frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= a / (\frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} + k)}{(k_{BASE})}) * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{a*ethAmount*k_{BASE}}{erc20Amount*(k_{BASE} + k)} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{a*ethAmount*k_{BASE}*(THETA_{BASE} - \theta)}{erc20Amount*(k_{BASE} + k)*THETA_{BASE}} \\\\
// amountOut = amountIn * _op.ethAmount * K_BASE * (THETA_BASE - _op.theta) / _op.erc20Amount / (K_BASE + _op.K) / THETA_BASE;
*/
amountOut = amountIn.mul(_op.ethAmount).mul(K_BASE).mul(THETA_BASE.sub(_op.theta)).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
if (_op.theta != 0) {
// fee = amountIn * _op.ethAmount * K_BASE * (_op.theta) / _op.erc20Amount / (K_BASE + _op.K) / THETA_BASE;
fee = amountIn.mul(_op.ethAmount).mul(K_BASE).mul(_op.theta).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
}
return (amountOut, fee);
}
// get estimated amountOut for token1 (ERC20 token) when swapWithExact
function calcOutToken1(uint256 amountIn, OraclePrice memory _op) public pure returns (uint256 amountOut, uint256 fee) {
/*
y &= b*P_{s}^{'}*\frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= b * \frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} - k)}{(k_{BASE})} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{b*erc20Amount*(k_{BASE} - k)*(THETA_{BASE} - \theta)}{ethAmount*k_{BASE}*THETA_{BASE}} \\\\
// amountOut = amountIn * _op.erc20Amount * (K_BASE - _op.K) * (THETA_BASE - _op.theta) / _op.ethAmount / K_BASE / THETA_BASE;
*/
amountOut = amountIn.mul(_op.erc20Amount).mul(K_BASE.sub(_op.K)).mul(THETA_BASE.sub(_op.theta)).div(_op.ethAmount).div(K_BASE).div(THETA_BASE);
if (_op.theta != 0) {
// fee = amountIn * _op.theta / THETA_BASE;
fee = amountIn.mul(_op.theta).div(THETA_BASE);
}
return (amountOut, fee);
}
// get estimate amountInNeeded for token0 (WETH) when swapForExact
function calcInNeededToken0(uint256 amountOut, OraclePrice memory _op) public pure returns (uint256 amountInNeeded, uint256 fee) {
// inverse of calcOutToken1
// amountOut = amountIn.mul(_op.erc20Amount).mul(K_BASE.sub(_op.K)).mul(THETA_BASE.sub(_op.theta)).div(_op.ethAmount).div(K_BASE).div(THETA_BASE);
amountInNeeded = amountOut.mul(_op.ethAmount).mul(K_BASE).mul(THETA_BASE).div(_op.erc20Amount).div(K_BASE.sub(_op.K)).div(THETA_BASE.sub(_op.theta));
if (_op.theta != 0) {
// fee = amountIn * _op.theta / THETA_BASE;
fee = amountInNeeded.mul(_op.theta).div(THETA_BASE);
}
return (amountInNeeded, fee);
}
// get estimate amountInNeeded for token1 (ERC20 token) when swapForExact
function calcInNeededToken1(uint256 amountOut, OraclePrice memory _op) public pure returns (uint256 amountInNeeded, uint256 fee) {
// inverse of calcOutToken0
// amountOut = amountIn.mul(_op.ethAmount).mul(K_BASE).mul(THETA_BASE.sub(_op.theta)).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
amountInNeeded = amountOut.mul(_op.erc20Amount).mul(K_BASE.add(_op.K)).mul(THETA_BASE).div(_op.ethAmount).div(K_BASE).div(THETA_BASE.sub(_op.theta));
if (_op.theta != 0) {
// fee = amountIn * _op.ethAmount * K_BASE * (_op.theta) / _op.erc20Amount / (K_BASE + _op.K) / THETA_BASE;
fee = amountInNeeded.mul(_op.ethAmount).mul(K_BASE).mul(_op.theta).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
}
return (amountInNeeded, fee);
}
function _queryOracle(address token, CoFiX_OP op, bytes memory data) internal returns (uint256, uint256, uint256, uint256, uint256) {
return ICoFiXController(ICoFiXFactory(factory).getController()).queryOracle{value: msg.value}(token, uint8(op), data);
}
// Safe WETH transfer function, just in case not having enough WETH. CoFi holder will earn these fees.
function _safeSendFeeForCoFiHolder(address _token0, uint256 _fee) internal {
address feeReceiver = ICoFiXFactory(factory).getFeeReceiver();
if (feeReceiver == address(0)) {
return; // if feeReceiver not set, theta fee keeps in pair pool
}
_safeSendFee(_token0, feeReceiver, _fee); // transfer fee to protocol fee reward pool for CoFi holders
}
// Safe WETH transfer function, just in case not having enough WETH. LP will earn these fees.
function _safeSendFeeForLP(address _token0, address _token1, uint256 _fee) internal {
address feeVault = ICoFiXFactory(factory).getFeeVaultForLP(_token1);
if (feeVault == address(0)) {
return; // if fee vault not set, theta fee keeps in pair pool
}
_safeSendFee(_token0, feeVault, _fee); // transfer fee to protocol fee reward pool for LP
}
function _safeSendFee(address _token0, address _receiver, uint256 _fee) internal {
uint256 wethBal = IERC20(_token0).balanceOf(address(this));
if (_fee > wethBal) {
_fee = wethBal;
}
if (_fee > 0) _safeTransfer(_token0, _receiver, _fee);
}
}
// UNI & CoFi Rocks
|
get estimated amountOut for token1 (ERC20 token) when swapWithExact amountOut = amountIn _op.erc20Amount (K_BASE - _op.K) (THETA_BASE - _op.theta) / _op.ethAmount / K_BASE / THETA_BASE;
|
function calcOutToken1(uint256 amountIn, OraclePrice memory _op) public pure returns (uint256 amountOut, uint256 fee) {
amountOut = amountIn.mul(_op.erc20Amount).mul(K_BASE.sub(_op.K)).mul(THETA_BASE.sub(_op.theta)).div(_op.ethAmount).div(K_BASE).div(THETA_BASE);
y &= b*P_{s}^{'}*\frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= b * \frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} - k)}{(k_{BASE})} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{b*erc20Amount*(k_{BASE} - k)*(THETA_{BASE} - \theta)}{ethAmount*k_{BASE}*THETA_{BASE}} \\\\
if (_op.theta != 0) {
fee = amountIn.mul(_op.theta).div(THETA_BASE);
}
return (amountOut, fee);
}
| 1,072,113
|
./partial_match/1/0xd40cADE3f71C20Ba6FE940E431c890dC100E97d6/sources/Rewards.sol
|
admin: reset periodFinish, lastUpdateTime, rewardRate
|
function notifyRewardAmount(uint256 reward)
external override
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
| 2,786,432
|
// contracts/DungeonsAndDragonsCharacter.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "./ERC721PresetMinterPauserAutoId.sol";
import "./extensions/Strings.sol";
import '@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol';
import '@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol';
import '@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol';
contract DungeonsAndDragonsCharacter is ERC721PresetMinterPauserAutoId, VRFConsumerBaseV2 {
using Strings for string;
event FulfillRandomness(uint256,uint256[]);
event RequestId(address,uint256);
VRFCoordinatorV2Interface COORDINATOR;
LinkTokenInterface LINKTOKEN;
// Your subscription ID.
uint64 s_subscriptionId;
// Rinkeby coordinator. For other networks,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
address vrfCoordinator = 0x6168499c0cFfCaCD319c818142124B7A15E857ab;
// Rinkeby LINK token contract. For other networks,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
address link = 0x01BE23585060835E02B77ef475b0Cc51aA1e0709;
// The gas lane to use, which specifies the maximum gas price to bump to.
// For a list of available gas lanes on each network,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
bytes32 keyHash = 0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc;
// Depends on the number of requested values that you want sent to the
// fulfillRandomWords() function. Storing each word costs about 20,000 gas,
// so 100,000 is a safe default for this example contract. Test and adjust
// this limit based on the network that you select, the size of the request,
// and the processing of the callback request in the fulfillRandomWords()
// function.
uint32 callbackGasLimit = 100000;
// The default is 3, but you can set this higher.
uint16 requestConfirmations = 3;
// For this example, retrieve 2 random values in one request.
// Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
uint32 numWords = 2;
bool public flag;
uint256 public tag;
struct Character {
uint256 strength;
uint256 dexterity;
uint256 constitution;
uint256 intelligence;
uint256 wisdom;
uint256 charisma;
uint256 experience;
string name;
}
Character[] public characters;
mapping(uint256 => string) requestToCharacterName;
mapping(uint256 => address) requestToSender;
mapping(uint256 => uint256) requestToRandnum;
constructor(uint64 subscriptionId,string memory tokenURI)
public
VRFConsumerBaseV2(vrfCoordinator)
ERC721PresetMinterPauserAutoId("DungeonsAndDragonsCharacter", "D&D",tokenURI)
{
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
LINKTOKEN = LinkTokenInterface(link);
s_subscriptionId = subscriptionId;
}
function requestNewRandomCharacter(
string memory name
) public returns (uint256) {
// Will revert if subscription is not set and funded.
uint256 requestId = COORDINATOR.requestRandomWords(keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords);
emit RequestId(msg.sender,requestId);
requestToCharacterName[requestId] = name;
requestToSender[requestId] = msg.sender;
return requestId;
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenId, _tokenURI);
}
function fulfillRandomWords(
uint256 requestId, /* requestId */
uint256[] memory randomWords)
internal override
{
requestToRandnum[requestId] = randomWords[0];
emit FulfillRandomness(requestId,randomWords);
}
function blindCharacter(uint256 requestId) public {
uint256 randomNum = requestToRandnum[requestId];
uint256 newId = characters.length;
uint256 strength = (randomNum % 100);
uint256 dexterity = ((randomNum % 10000) / 100 );
uint256 constitution = ((randomNum % 1000000) / 10000 );
uint256 intelligence = ((randomNum % 100000000) / 1000000 );
uint256 wisdom = ((randomNum % 10000000000) / 100000000 );
uint256 charisma = ((randomNum % 1000000000000) / 10000000000);
uint256 experience = 0;
characters.push(
Character(
strength,
dexterity,
constitution,
intelligence,
wisdom,
charisma,
experience,
requestToCharacterName[requestId]
)
);
_safeMint(requestToSender[requestId], newId);
}
function getLevel(uint256 tokenId) public view returns (uint256) {
return sqrt(characters[tokenId].experience);
}
function getNumberOfCharacters() public view returns (uint256) {
return characters.length;
}
function getCharacterOverView(uint256 tokenId)
public
view
returns (
string memory,
uint256,
uint256,
uint256
)
{
return (
characters[tokenId].name,
characters[tokenId].strength + characters[tokenId].dexterity + characters[tokenId].constitution + characters[tokenId].intelligence + characters[tokenId].wisdom + characters[tokenId].charisma,
getLevel(tokenId),
characters[tokenId].experience
);
}
function sqrt(uint256 x) internal view returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
// expand to more random
// function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) {
// expandedValues = new uint256[](n);
// for (uint256 i = 0; i < n; i++) {
// expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
// }
// return expandedValues;
// }
}
|
Will revert if subscription is not set and funded.
|
function requestNewRandomCharacter(
string memory name
) public returns (uint256) {
uint256 requestId = COORDINATOR.requestRandomWords(keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords);
emit RequestId(msg.sender,requestId);
requestToCharacterName[requestId] = name;
requestToSender[requestId] = msg.sender;
return requestId;
}
| 12,707,894
|
pragma solidity ^0.5.0;
import './ERC721.sol';
/// @notice The Ecommerce Token that implements the ERC721 token with mint function
/// @author Merunas Grincalaitis <merunasgrincalaitis@gmail.com>
contract EcommerceToken is ERC721 {
address public ecommerce;
bool public isEcommerceSet = false;
/// @notice To generate a new token for the specified address
/// @param _to The receiver of this new token
/// @param _tokenId The new token id, must be unique
function mint(address _to, uint256 _tokenId) public {
require(msg.sender == ecommerce, 'Only the ecommerce contract can mint new tokens');
_mint(_to, _tokenId);
}
/// @notice To set the ecommerce smart contract address
function setEcommerce(address _ecommerce) public {
require(!isEcommerceSet, 'The ecommerce address can only be set once');
require(_ecommerce != address(0), 'The ecommerce address cannot be empty');
isEcommerceSet = true;
ecommerce = _ecommerce;
}
}
/// @notice The main ecommerce contract to buy and sell ERC-721 tokens representing physical or digital products because we are dealing with non-fungible tokens, there will be only 1 stock per product
/// @author Merunas Grincalaitis <merunasgrincalaitis@gmail.com>
contract Ecommerce {
// We need the following:
/*
- A function to publish, sell products with unique token ids
- A function to buy products
- A function to mark purchased products as completed by the seller
- A function to get all the orders
- A function to get the recent products
*/
struct Product {
uint256 id;
string title;
string description;
uint256 date;
address payable owner;
uint256 price;
string image;
}
struct Order {
uint256 id;
string nameSurname;
string lineOneDirection;
string lineTwoDirection;
bytes32 city;
bytes32 stateRegion;
uint256 postalCode;
bytes32 country;
uint256 phone;
string state; // Either 'pending', 'completed'
}
// Seller address => products
mapping(address => Product[]) public sellerProducts; // The published products by the seller
// Seller address => products
mapping(address => Order[]) public pendingSellerOrders; // The products waiting to be fulfilled by the seller, used by sellers to check which orders have to be filled
// Buyer address => products
mapping(address => Order[]) public pendingBuyerOrders; // The products that the buyer purchased waiting to be sent
// Seller address => products
mapping(address => Order[]) public completedSellerOrders; // A history of past orders fulfilled by the seller
// Buyer address => products
mapping(address => Order[]) public completedBuyerOrders; // A history of past orders made by this buyer
// Product id => product
mapping(uint256 => Product) public productById;
// Product id => order
mapping(uint256 => Order) public orderById;
// Product id => true or false
mapping(uint256 => bool) public productExists;
Product[] public products;
Order[] public orders;
uint256 public lastId;
address public token;
uint256 public lastPendingSellerOrder;
uint256 public lastPendingBuyerOrder;
/// @notice To setup the address of the ERC-721 token to use for this contract
/// @param _token The token address
constructor(address _token) public {
token = _token;
}
/// @notice To publish a product as a seller
/// @param _title The title of the product
/// @param _description The description of the product
/// @param _price The price of the product in ETH
/// @param _image The image URL of the product
function publishProduct(string memory _title, string memory _description, uint256 _price, string memory _image) public {
require(bytes(_title).length > 0, 'The title cannot be empty');
require(bytes(_description).length > 0, 'The description cannot be empty');
require(_price > 0, 'The price cannot be empty');
require(bytes(_image).length > 0, 'The image cannot be empty');
Product memory p = Product(lastId, _title, _description, now, msg.sender, _price * 1e18 , _image);
products.push(p);
sellerProducts[msg.sender].push(p);
productById[lastId] = p;
productExists[lastId] = true;
EcommerceToken(token).mint(address(this), lastId); // Create a new token for this product which will be owned by this contract until sold
lastId++;
}
/// @notice To buy a new product, note that the seller must authorize this contract to manage the token
/// @param _id The id of the product to buy
/// @param _nameSurname The name and surname of the buyer
/// @param _lineOneDirection The first line for the user address
/// @param _lineTwoDirection The second, optional user address line
/// @param _city Buyer's city
/// @param _stateRegion The state or region where the buyer lives
/// @param _postalCode The postal code of his location
/// @param _country Buyer's country
/// @param _phone The optional phone number for the shipping company
function buyProduct(uint256 _id, string memory _nameSurname, string memory _lineOneDirection, string memory _lineTwoDirection, bytes32 _city, bytes32 _stateRegion, uint256 _postalCode, bytes32 _country, uint256 _phone) public payable {
// The line 2 address and phone are optional, the rest are mandatory
require(productExists[_id], 'The product must exist to be purchased');
require(bytes(_nameSurname).length > 0, 'The name and surname must be set');
require(bytes(_lineOneDirection).length > 0, 'The line one direction must be set');
require(_city.length > 0, 'The city must be set');
require(_stateRegion.length > 0, 'The state or region must be set');
require(_postalCode > 0, 'The postal code must be set');
require(_country > 0, 'The country must be set');
Product memory p = productById[_id];
Order memory newOrder = Order(_id, _nameSurname, _lineOneDirection, _lineTwoDirection, _city, _stateRegion, _postalCode, _country, _phone, 'pending');
require(msg.value >= p.price, "The payment must be larger or equal than the products price");
// Return the excess ETH sent by the buyer
if(msg.value > p.price) msg.sender.transfer(msg.value - p.price);
pendingSellerOrders[p.owner].push(newOrder);
pendingBuyerOrders[msg.sender].push(newOrder);
orders.push(newOrder);
orderById[_id] = newOrder;
lastPendingSellerOrder = pendingSellerOrders[p.owner].length > 0 ? pendingSellerOrders[p.owner].length - 1 : 0;
lastPendingBuyerOrder = pendingBuyerOrders[p.owner].length > 0 ? pendingBuyerOrders[p.owner].length - 1 : 0;
EcommerceToken(token).transferFrom(p.owner, msg.sender, _id); // Transfer the product token to the new owner
p.owner.transfer(p.price);
}
/// @notice To mark an order as completed
/// @param _id The id of the order which is the same for the product id
function markOrderCompleted(uint256 _id) public {
Order memory order = orderById[_id];
Product memory product = productById[_id];
require(product.owner == msg.sender, 'Only the seller can mark the order as completed');
order.state = 'completed';
// Delete the seller order from the array of pending orders
for(uint256 i = 0; i < pendingSellerOrders[product.owner].length; i++) {
if(pendingSellerOrders[product.owner][i].id == _id) {
Order memory lastElement = orderById[lastPendingSellerOrder];
pendingSellerOrders[product.owner][i] = lastElement;
pendingSellerOrders[product.owner].length--;
lastPendingSellerOrder--;
}
}
// Delete the seller order from the array of pending orders
for(uint256 i = 0; i < pendingBuyerOrders[msg.sender].length; i++) {
if(pendingBuyerOrders[msg.sender][i].id == order.id) {
Order memory lastElement = orderById[lastPendingBuyerOrder];
pendingBuyerOrders[msg.sender][i] = lastElement;
pendingBuyerOrders[msg.sender].length--;
lastPendingBuyerOrder--;
}
}
completedSellerOrders[product.owner].push(order);
completedBuyerOrders[msg.sender].push(order);
orderById[_id] = order;
}
/// @notice To get the latest product ids so that we can get each product independently
/// @param _amount The number of products to get
/// @return uint256[] The array of ids for the latest products added
function getLatestProductIds(uint256 _amount) public view returns(uint256[] memory) {
// If you're requesting more products than available, return only the available
uint256 length = products.length;
uint256 counter = (_amount > length) ? length : _amount;
uint256 condition = (_amount > length) ? 0 : (length - _amount);
uint256[] memory ids = new uint256[](_amount > length ? _amount : length);
uint256 increment = 0;
// Loop backwards to get the most recent products first
for(int256 i = int256(counter); i >= int256(condition); i--) {
ids[increment] = products[uint256(i)].id;
}
return ids;
}
/// @notice To get a single product broken down by properties
/// @param _id The id of the product to get
/// @return The product properties including all of them
function getProduct(uint256 _id) public view returns(uint256 id, string memory title, string memory description, uint256 date, address payable owner, uint256 price, string memory image) {
Product memory p = productById[_id];
id = p.id;
title = p.title;
description = p.description;
date = p.date;
owner = p.owner;
price = p.price;
image = p.image;
}
/// @notice To get the latest ids for a specific type of order, if it's a seller type of order the _owner address must be the seller's
/// @param _type The type of order which can be 'pending-seller', 'pending-buyer', 'completed-seller' and 'completed-buyer'
/// @param _owner The address from which get the order data
/// @param _amount How many ids to get
/// @return uint256[] The most recent ids sorted from newest to oldest
function getLatestOrderIds(string memory _type, address _owner, uint256 _amount) public view returns(uint256[] memory) {
// If you're requesting more products than available, return only the available
uint256 length;
uint256 counter;
uint256 condition;
uint256[] memory ids;
uint256 increment = 0;
if(compareStrings(_type, 'pending-seller')) {
length = pendingSellerOrders[_owner].length;
counter = (_amount > length) ? length : _amount;
condition = (_amount > length) ? 0 : (length - _amount);
ids = new uint256[](_amount > length ? _amount : length);
for(int256 i = int256(counter); i >= int256(condition); i--) {
ids[increment] = uint256(pendingSellerOrders[_owner][uint256(i)].id);
}
} else if(compareStrings(_type, 'pending-buyer')) {
length = pendingBuyerOrders[_owner].length;
counter = (_amount > length) ? length : _amount;
condition = (_amount > length) ? 0 : (length - _amount);
ids = new uint256[](_amount > length ? _amount : length);
for(int256 i = int256(counter); i >= int256(condition); i--) {
ids[increment] = uint256(pendingBuyerOrders[_owner][uint256(i)].id);
}
} else if(compareStrings(_type, 'completed-seller')) {
length = completedSellerOrders[_owner].length;
counter = (_amount > length) ? length : _amount;
condition = (_amount > length) ? 0 : (length - _amount);
ids = new uint256[](_amount > length ? _amount : length);
for(int256 i = int256(counter); i >= int256(condition); i--) {
ids[increment] = uint256(completedSellerOrders[_owner][uint256(i)].id);
}
} else if(compareStrings(_type, 'completed-buyer')) {
length = completedBuyerOrders[_owner].length;
counter = (_amount > length) ? length : _amount;
condition = (_amount > length) ? 0 : (length - _amount);
ids = new uint256[](_amount > length ? _amount : length);
for(int256 i = int256(counter); i >= int256(condition); i--) {
ids[increment] = uint256(completedBuyerOrders[_owner][uint256(i)].id);
}
}
return ids;
}
/// @notice To get an individual order with all the parameters
/// @param _type The type of order which can be 'pending-seller', 'pending-buyer', 'completed-seller' and 'completed-buyer'
/// @param _owner The address from which get the order data
/// @param _id The order id
/// @return Returns all the parameters for that specific order
function getOrder(string memory _type, address _owner, uint256 _id) public view returns(uint256 id, string memory nameSurname, string memory lineOneDirection, string memory lineTwoDirection, bytes32 city, bytes32 stateRegion, uint256 postalCode, bytes32 country, uint256 phone, string memory state) {
Order memory o;
if(compareStrings(_type, 'pending-seller')) {
o = pendingSellerOrders[_owner][_id];
} else if(compareStrings(_type, 'pending-buyer')) {
o = pendingBuyerOrders[_owner][_id];
} else if(compareStrings(_type, 'completed-seller')) {
o = completedSellerOrders[_owner][_id];
} else if(compareStrings(_type, 'completed-buyer')) {
o = completedBuyerOrders[_owner][_id];
}
id = o.id;
nameSurname = o.nameSurname;
lineOneDirection = o.lineOneDirection;
lineTwoDirection = o.lineTwoDirection;
city = o.city;
stateRegion = o.stateRegion;
postalCode = o.postalCode;
country = o.country;
phone = o.phone;
state = o.state;
}
/// @notice To compare two strings since we can't use the normal operator in solidity
/// @param a The first string
/// @param b The second string
/// @return bool If they are equal or not
function compareStrings(string memory a, string memory b) public pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
}
|
To get an individual order with all the parameters _type The type of order which can be 'pending-seller', 'pending-buyer', 'completed-seller' and 'completed-buyer' _owner The address from which get the order data _id The order id return Returns all the parameters for that specific order
|
function getOrder(string memory _type, address _owner, uint256 _id) public view returns(uint256 id, string memory nameSurname, string memory lineOneDirection, string memory lineTwoDirection, bytes32 city, bytes32 stateRegion, uint256 postalCode, bytes32 country, uint256 phone, string memory state) {
Order memory o;
if(compareStrings(_type, 'pending-seller')) {
o = pendingSellerOrders[_owner][_id];
o = pendingBuyerOrders[_owner][_id];
o = completedSellerOrders[_owner][_id];
o = completedBuyerOrders[_owner][_id];
}
id = o.id;
nameSurname = o.nameSurname;
lineOneDirection = o.lineOneDirection;
lineTwoDirection = o.lineTwoDirection;
city = o.city;
stateRegion = o.stateRegion;
postalCode = o.postalCode;
country = o.country;
phone = o.phone;
state = o.state;
}
| 13,118,530
|
pragma solidity 0.5.10;
/**
* Copyright © 2017-2019 Ramp Network sp. z o.o. All rights reserved (MIT License).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
interface Erc20Token {
/**
* Send `_value` of tokens from `msg.sender` to `_to`
*
* @param _to The recipient address
* @param _value The amount of tokens to be transferred
* @return Indication if the transfer was successful
*/
function transfer(address _to, uint256 _value) external returns (bool success);
/**
* Approve `_spender` to withdraw from sender's account multiple times, up to `_value`
* amount. If this function is called again it overwrites the current allowance with _value.
*
* @param _spender The address allowed to operate on sender's tokens
* @param _value The amount of tokens allowed to be transferred
* @return Indication if the approval was successful
*/
function approve(address _spender, uint256 _value) external returns (bool success);
/**
* Transfer tokens on behalf of `_from`, provided it was previously approved.
*
* @param _from The transfer source address (tokens owner)
* @param _to The transfer destination address
* @param _value The amount of tokens to be transferred
* @return Indication if the approval was successful
*/
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
/**
* Returns the account balance of another account with address `_owner`.
*/
function balanceOf(address _owner) external view returns (uint256);
}
contract AssetAdapter {
uint16 public ASSET_TYPE;
constructor(
uint16 assetType
) internal {
ASSET_TYPE = assetType;
}
/**
* Ensure the described asset is sent to the given address.
* Should revert if the transfer failed, but callers must also handle `false` being returned,
* much like ERC-20's `transfer`.
*/
function rawSendAsset(
bytes memory assetData,
uint256 _amount,
address payable _to
) internal returns (bool success); // solium-disable-line indentation
// indentation rule bug ^ https://github.com/duaraghav8/Ethlint/issues/268
/**
* Ensure the described asset is sent to this contract.
* Should revert if the transfer failed, but callers must also handle `false` being returned,
* much like ERC-20's `transfer`.
*/
function rawLockAsset(
uint256 amount,
address payable _from
) internal returns (bool success) {
return RampInstantPoolInterface(_from).sendFundsToSwap(amount);
}
function getAmount(bytes memory assetData) internal pure returns (uint256);
/**
* Verify that the passed asset data can be handled by this adapter and given pool.
*
* @dev it's sufficient to use this only when creating a new swap -- all the other swap
* functions first check if the swap hash is valid, while a swap hash with invalid
* asset type wouldn't be created at all.
*
* @dev asset type is 2 bytes long, and it's at offset 32 in `assetData`'s memory (the first 32
* bytes are the data length). We load the word at offset 2 (it ends with the asset type bytes),
* and retrieve its last 2 bytes into a `uint16` variable.
*/
modifier checkAssetTypeAndData(bytes memory assetData, address _pool) {
uint16 assetType;
// solium-disable-next-line security/no-inline-assembly
assembly {
assetType := and(
mload(add(assetData, 2)),
0xffff
)
}
require(assetType == ASSET_TYPE, "invalid asset type");
checkAssetData(assetData, _pool);
_;
}
function checkAssetData(bytes memory assetData, address _pool) internal view;
function () external payable {
revert("this contract cannot receive ether");
}
}
contract RampInstantPoolInterface {
uint16 public ASSET_TYPE;
function sendFundsToSwap(uint256 _amount)
public /*onlyActive onlySwapsContract isWithinLimits*/ returns(bool success);
}
contract RampInstantTokenPoolInterface is RampInstantPoolInterface {
address public token;
}
contract Ownable {
address public owner;
event OwnerChanged(address oldOwner, address newOwner);
constructor() internal {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "only the owner can call this");
_;
}
function changeOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
emit OwnerChanged(msg.sender, _newOwner);
}
}
contract WithStatus is Ownable {
enum Status {
STOPPED,
RETURN_ONLY,
FINALIZE_ONLY,
ACTIVE
}
event StatusChanged(Status oldStatus, Status newStatus);
Status public status = Status.ACTIVE;
function setStatus(Status _status) external onlyOwner {
emit StatusChanged(status, _status);
status = _status;
}
modifier statusAtLeast(Status _status) {
require(status >= _status, "invalid contract status");
_;
}
}
contract WithOracles is Ownable {
mapping (address => bool) oracles;
constructor() internal {
oracles[msg.sender] = true;
}
function approveOracle(address _oracle) external onlyOwner {
oracles[_oracle] = true;
}
function revokeOracle(address _oracle) external onlyOwner {
oracles[_oracle] = false;
}
modifier isOracle(address _oracle) {
require(oracles[_oracle], "invalid oracle address");
_;
}
modifier onlyOracleOrPool(address _pool, address _oracle) {
require(
msg.sender == _pool || (msg.sender == _oracle && oracles[msg.sender]),
"only the oracle or the pool can call this"
);
_;
}
}
contract WithSwapsCreator is Ownable {
address internal swapCreator;
event SwapCreatorChanged(address _oldCreator, address _newCreator);
constructor() internal {
swapCreator = msg.sender;
}
function changeSwapCreator(address _newCreator) public onlyOwner {
swapCreator = _newCreator;
emit SwapCreatorChanged(msg.sender, _newCreator);
}
modifier onlySwapCreator() {
require(msg.sender == swapCreator, "only the swap creator can call this");
_;
}
}
contract AssetAdapterWithFees is Ownable, AssetAdapter {
uint16 public feeThousandthsPercent;
uint256 public minFeeAmount;
constructor(uint16 _feeThousandthsPercent, uint256 _minFeeAmount) public {
require(_feeThousandthsPercent < (1 << 16), "fee % too high");
require(_minFeeAmount <= (1 << 255), "minFeeAmount too high");
feeThousandthsPercent = _feeThousandthsPercent;
minFeeAmount = _minFeeAmount;
}
function rawAccumulateFee(bytes memory assetData, uint256 _amount) internal;
function accumulateFee(bytes memory assetData) internal {
rawAccumulateFee(assetData, getFee(getAmount(assetData)));
}
function withdrawFees(
bytes calldata assetData,
address payable _to
) external /*onlyOwner*/ returns (bool success); // solium-disable-line indentation
function getFee(uint256 _amount) internal view returns (uint256) {
uint256 fee = _amount * feeThousandthsPercent / 100000;
return fee < minFeeAmount
? minFeeAmount
: fee;
}
function getAmountWithFee(bytes memory assetData) internal view returns (uint256) {
uint256 baseAmount = getAmount(assetData);
return baseAmount + getFee(baseAmount);
}
function lockAssetWithFee(
bytes memory assetData,
address payable _from
) internal returns (bool success) {
return rawLockAsset(getAmountWithFee(assetData), _from);
}
function sendAssetWithFee(
bytes memory assetData,
address payable _to
) internal returns (bool success) {
return rawSendAsset(assetData, getAmountWithFee(assetData), _to);
}
function sendAssetKeepingFee(
bytes memory assetData,
address payable _to
) internal returns (bool success) {
bool result = rawSendAsset(assetData, getAmount(assetData), _to);
if (result) accumulateFee(assetData);
return result;
}
}
/**
* The main contract managing Ramp Swaps escrows lifecycle: create, release or return.
* Uses an abstract AssetAdapter to carry out the transfers and handle the particular asset data.
* With a corresponding off-chain oracle protocol allows for atomic-swap-like transfer between
* fiat currencies and crypto assets.
*
* @dev an active swap is represented by a hash of its details, mapped to its escrow expiration
* timestamp. When the swap is created, its end time is set a given amount of time in the future
* (but within {MIN,MAX}_SWAP_LOCK_TIME_S).
* The hashed swap details are:
* * address pool: the `RampInstantPool` contract that sells the crypto asset;
* * address receiver: the user that buys the crypto asset;
* * address oracle: address of the oracle that handles this particular swap;
* * bytes assetData: description of the crypto asset, handled by an AssetAdapter;
* * bytes32 paymentDetailsHash: hash of the fiat payment details: account numbers, fiat value
* and currency, and the transfer reference (title), that can be verified off-chain.
*
* @author Ramp Network sp. z o.o.
*/
contract RampInstantEscrows
is Ownable, WithStatus, WithOracles, WithSwapsCreator, AssetAdapterWithFees {
/// @dev contract version, defined in semver
string public constant VERSION = "0.5.1";
uint32 internal constant MIN_ACTUAL_TIMESTAMP = 1000000000;
/// @notice lock time limits for pool's assets, after which unreleased escrows can be returned
uint32 internal constant MIN_SWAP_LOCK_TIME_S = 24 hours;
uint32 internal constant MAX_SWAP_LOCK_TIME_S = 30 days;
event Created(bytes32 indexed swapHash);
event Released(bytes32 indexed swapHash);
event PoolReleased(bytes32 indexed swapHash);
event Returned(bytes32 indexed swapHash);
event PoolReturned(bytes32 indexed swapHash);
/**
* @notice Mapping from swap details hash to its end time (as a unix timestamp).
* After the end time the swap can be cancelled, and the funds will be returned to the pool.
*/
mapping (bytes32 => uint32) internal swaps;
/**
* Swap creation, called by the Ramp Network. Checks swap parameters and ensures the crypto
* asset is locked on this contract.
*
* Emits a `Created` event with the swap hash.
*/
function create(
address payable _pool,
address _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash,
uint32 lockTimeS
)
external
statusAtLeast(Status.ACTIVE)
onlySwapCreator()
isOracle(_oracle)
checkAssetTypeAndData(_assetData, _pool)
returns
(bool success)
{
require(
lockTimeS >= MIN_SWAP_LOCK_TIME_S && lockTimeS <= MAX_SWAP_LOCK_TIME_S,
"lock time outside limits"
);
bytes32 swapHash = getSwapHash(
_pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash
);
requireSwapNotExists(swapHash);
// Set up swap status before transfer, to avoid reentrancy attacks.
// Even if a malicious token is somehow passed to this function (despite the oracle
// signature of its details), the state of this contract is already fully updated,
// so it will behave correctly (as it would be a separate call).
// solium-disable-next-line security/no-block-members
swaps[swapHash] = uint32(block.timestamp) + lockTimeS;
require(
lockAssetWithFee(_assetData, _pool),
"escrow lock failed"
);
emit Created(swapHash);
return true;
}
/**
* Swap release, which transfers the crypto asset to the receiver and removes the swap from
* the active swap mapping. Normally called by the swap's oracle after it confirms a matching
* wire transfer on pool's bank account. Can be also called by the pool, for example in case
* of a dispute, when the parties reach an agreement off-chain.
*
* Emits a `Released` or `PoolReleased` event with the swap's hash.
*/
function release(
address _pool,
address payable _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash
) external statusAtLeast(Status.FINALIZE_ONLY) onlyOracleOrPool(_pool, _oracle) {
bytes32 swapHash = getSwapHash(
_pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash
);
requireSwapCreated(swapHash);
// Delete the swap status before transfer, to avoid reentrancy attacks.
swaps[swapHash] = 0;
require(
sendAssetKeepingFee(_assetData, _receiver),
"asset release failed"
);
if (msg.sender == _pool) {
emit PoolReleased(swapHash);
} else {
emit Released(swapHash);
}
}
/**
* Swap return, which transfers the crypto asset back to the pool and removes the swap from
* the active swap mapping. Can be called by the pool or the swap's oracle, but only if the
* escrow lock time expired.
*
* Emits a `Returned` or `PoolReturned` event with the swap's hash.
*/
function returnFunds(
address payable _pool,
address _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash
) external statusAtLeast(Status.RETURN_ONLY) onlyOracleOrPool(_pool, _oracle) {
bytes32 swapHash = getSwapHash(
_pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash
);
requireSwapExpired(swapHash);
// Delete the swap status before transfer, to avoid reentrancy attacks.
swaps[swapHash] = 0;
require(
sendAssetWithFee(_assetData, _pool),
"asset return failed"
);
if (msg.sender == _pool) {
emit PoolReturned(swapHash);
} else {
emit Returned(swapHash);
}
}
/**
* Given all valid swap details, returns its status. The return can be:
* 0: the swap details are invalid, swap doesn't exist, or was already released/returned.
* >1: the swap was created, and the value is a timestamp indicating end of its lock time.
*/
function getSwapStatus(
address _pool,
address _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash
) external view returns (uint32 status) {
bytes32 swapHash = getSwapHash(
_pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash
);
return swaps[swapHash];
}
/**
* Calculates the swap hash used to reference the swap in this contract's storage.
*/
function getSwapHash(
address _pool,
address _receiver,
address _oracle,
bytes32 assetHash,
bytes32 _paymentDetailsHash
) internal pure returns (bytes32) {
return keccak256(
abi.encodePacked(
_pool, _receiver, _oracle, assetHash, _paymentDetailsHash
)
);
}
function requireSwapNotExists(bytes32 swapHash) internal view {
require(
swaps[swapHash] == 0,
"swap already exists"
);
}
function requireSwapCreated(bytes32 swapHash) internal view {
require(
swaps[swapHash] > MIN_ACTUAL_TIMESTAMP,
"swap invalid"
);
}
function requireSwapExpired(bytes32 swapHash) internal view {
require(
// solium-disable-next-line security/no-block-members
swaps[swapHash] > MIN_ACTUAL_TIMESTAMP && block.timestamp > swaps[swapHash],
"swap not expired or invalid"
);
}
}
contract TokenAdapter is AssetAdapterWithFees {
uint16 internal constant TOKEN_TYPE_ID = 2;
uint16 internal constant TOKEN_ASSET_DATA_LENGTH = 54;
mapping (address => uint256) internal accumulatedFees;
constructor() internal AssetAdapter(TOKEN_TYPE_ID) {}
/**
* @dev token assetData bytes contents:
* offset length type contents
* +00 32 uint256 data length (== 0x36 == 54 bytes)
* +32 2 uint16 asset type (== TOKEN_TYPE_ID == 2)
* +34 32 uint256 token amount in units
* +66 20 address token contract address
*/
function getAmount(bytes memory assetData) internal pure returns (uint256 amount) {
// solium-disable-next-line security/no-inline-assembly
assembly {
amount := mload(add(assetData, 34))
}
}
/**
* @dev To retrieve the address at offset 66, get the word at offset 54 and return its last
* 20 bytes. See `getAmount` for byte offsets table.
*/
function getTokenAddress(bytes memory assetData) internal pure returns (address tokenAddress) {
// solium-disable-next-line security/no-inline-assembly
assembly {
tokenAddress := and(
mload(add(assetData, 54)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
}
function rawSendAsset(
bytes memory assetData,
uint256 _amount,
address payable _to
) internal returns (bool success) {
Erc20Token token = Erc20Token(getTokenAddress(assetData));
return token.transfer(_to, _amount);
}
function rawAccumulateFee(bytes memory assetData, uint256 _amount) internal {
accumulatedFees[getTokenAddress(assetData)] += _amount;
}
function withdrawFees(
bytes calldata assetData,
address payable _to
) external onlyOwner returns (bool success) {
address token = getTokenAddress(assetData);
uint256 fees = accumulatedFees[token];
accumulatedFees[token] = 0;
require(Erc20Token(token).transfer(_to, fees), "fees transfer failed");
return true;
}
function checkAssetData(bytes memory assetData, address _pool) internal view {
require(assetData.length == TOKEN_ASSET_DATA_LENGTH, "invalid asset data length");
require(
RampInstantTokenPoolInterface(_pool).token() == getTokenAddress(assetData),
"invalid pool token address"
);
}
}
contract RampInstantTokenEscrows is RampInstantEscrows, TokenAdapter {
constructor(
uint16 _feeThousandthsPercent,
uint256 _minFeeAmount
) public AssetAdapterWithFees(_feeThousandthsPercent, _minFeeAmount) {}
}
|
To retrieve the address at offset 66, get the word at offset 54 and return its last 20 bytes. See `getAmount` for byte offsets table./ solium-disable-next-line security/no-inline-assembly
|
function getTokenAddress(bytes memory assetData) internal pure returns (address tokenAddress) {
assembly {
tokenAddress := and(
mload(add(assetData, 54)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
}
| 5,513,158
|
/**
Copyright (c) 2018, ZSC Dev Team
2018-10-19: v0.00.01
*/
pragma solidity ^0.4.25;
// pragma experimental ABIEncoderV2;
import "../../common/delegate.sol";
import "./Logistics_database.sol";
contract LogisticsCore is Delegate {
using LibString for *;
using LibInt for *;
/** @desc database address */
address private databaseAddr_;
/*************************************************/
/** @desc num total count */
uint private numTotalCount_;
/** @desc uint(num index) => string(original num name) */
mapping(uint => string) private numNames_;
/** @desc string(original num name) => uint(num index) */
mapping(string => uint) private numIds_;
/** @desc string(original num name) => bool(num exist flag) */
mapping(string => bool) private numExists_;
/** @desc string(original num name) => uint(num invalid count) */
mapping(string => uint) private numInvalidCounts_;
/*************************************************/
// Constructor
constructor() public {
databaseAddr_ = 0;
numTotalCount_ = 0;
}
modifier _checkDatabaseAddr() {
require(0 != databaseAddr_);
_;
}
modifier _onlyAdminOrHigher() {
require(checkDelegate(msg.sender, 2));
_;
}
function _addNum(string _num) private {
numNames_[numTotalCount_] = _num;
numIds_[_num] = numTotalCount_;
numTotalCount_ ++;
numExists_[_num] = true;
}
function _removeNum(string _num) private {
string memory lastNumName = "";
uint currentIndex = 0;
// check num total count
if (0 == numTotalCount_) {
return;
}
lastNumName = numNames_[numTotalCount_-1];
currentIndex = numIds_[_num];
numNames_[currentIndex] = lastNumName;
delete numNames_[numTotalCount_-1];
numIds_[lastNumName] = currentIndex;
delete numIds_[_num];
numTotalCount_ --;
numExists_[_num] = false;
}
function _getValidNumName(string _num) private view returns (string) {
return _num.concat("-", numInvalidCounts_[_num].toString());
}
function setup(address _databaseAddr) external _onlyOwner {
// check database address
require(0 != _databaseAddr);
databaseAddr_ = _databaseAddr;
}
// _updateType: 0 means overwrite, 1 means append
function updateTracks(string _num, string _tracks, uint8 _updateType) external _onlyAdminOrHigher _checkDatabaseAddr {
// check param
require(0 != bytes(_num).length);
require(0 != bytes(_tracks).length);
require((0 == _updateType) || (1 == _updateType));
// check num exist
require(numExists_[_num]);
// update tracks
LogisticsDatabase(databaseAddr_).updateTracks(_getValidNumName(_num), _tracks, _updateType);
}
function updateBrief(string _num, string _transNum, string _model,
uint16 _destinationCountry, uint8 _lastStatus) public _onlyAdminOrHigher _checkDatabaseAddr {
// check param
require(0 != bytes(_num).length);
if (!numExists_[_num]) {
// add num
_addNum(_num);
}
// update brief
LogisticsDatabase(databaseAddr_).updateBrief(_getValidNumName(_num), _transNum, _model, _destinationCountry, _lastStatus);
}
function updateBriefEx(string _num, string _brief) public _onlyAdminOrHigher _checkDatabaseAddr {
// check param
require(0 != bytes(_num).length);
require(0 != bytes(_brief).length);
if (!numExists_[_num]) {
// add num
_addNum(_num);
}
// update brief ex
LogisticsDatabase(databaseAddr_).updateBriefEx(_getValidNumName(_num), _brief);
}
function update(string _num, string _transNum,
string _model, uint16 _destinationCountry,
uint8 _lastStatus, string _tracks) external _onlyAdminOrHigher {
// update brief
updateBrief(_num, _transNum, _model, _destinationCountry, _lastStatus);
// update tracks from json(similar to)
if (0 != bytes(_tracks).length) {
this.updateTracks(_num, _tracks, 0);
}
}
function updateEx(string _num, string _info) external _onlyAdminOrHigher {
// update brief from json(similar to)
updateBriefEx(_num, _info);
// update tracks from json(similar to)
this.updateTracks(_num, _info, uint8(0));
}
function remove(string _num) external _onlyAdminOrHigher _checkDatabaseAddr {
// check param
require(0 != bytes(_num).length);
// check num exist
require(numExists_[_num]);
// remove database
LogisticsDatabase(databaseAddr_).remove(_getValidNumName(_num));
// remove num
_removeNum(_num);
}
function invalid(string _num) external _onlyAdminOrHigher {
// check param
require(0 != bytes(_num).length);
// check num exist
require(numExists_[_num]);
// remove num
_removeNum(_num);
numInvalidCounts_[_num] ++;
}
function exist(string _num) external view returns (bool) {
// check param
if (0 == bytes(_num).length) {
return false;
}
return numExists_[_num];
}
function number() external view returns (uint) {
return numTotalCount_;
}
function numberOfTracks(string _num) external view _checkDatabaseAddr returns (uint) {
// check param
if (0 == bytes(_num).length) {
return 0;
}
// check num exist
if (!numExists_[_num]) {
return 0;
}
return LogisticsDatabase(databaseAddr_).numberOfTracks(_getValidNumName(_num));
}
function numberOfInvalid(string _num) external view returns (uint) {
// check param
if (0 == bytes(_num).length) {
return 0;
}
return numInvalidCounts_[_num];
}
function getNumByIndex(uint _index) external view returns (string) {
if(numTotalCount_ <= _index) {
return "";
}
return numNames_[_index];
}
function getParcel(string _num) external view _checkDatabaseAddr returns (string, string, uint16, uint8, string) {
// check param
if (0 == bytes(_num).length) {
return ("", "", 0, 0, "");
}
// check num exist
if (!numExists_[_num]) {
return ("", "", 0, 0, "");
}
return LogisticsDatabase(databaseAddr_).getParcel(_getValidNumName(_num));
}
function getParcelEx(string _num) external view _checkDatabaseAddr returns (string) {
// check param
if (0 == bytes(_num).length) {
return "";
}
// check num exist
if (!numExists_[_num]) {
return "";
}
return LogisticsDatabase(databaseAddr_).getParcelEx(_num, _getValidNumName(_num));
}
function getTracks(string _num) external view _checkDatabaseAddr returns (string) {
// check param
if (0 == bytes(_num).length) {
return "";
}
// check num exist
if (!numExists_[_num]) {
return "";
}
return LogisticsDatabase(databaseAddr_).getTracks(_getValidNumName(_num));
}
function getTrackElement(string _num, uint _index, string _tag) external view _checkDatabaseAddr returns (string) {
// check param
if (0 == bytes(_num).length) {
return "";
}
// check num exist
if (!numExists_[_num]) {
return "";
}
return LogisticsDatabase(databaseAddr_).getTrackElement(_getValidNumName(_num), _index, _tag);
}
function getBrief(string _num) external view _checkDatabaseAddr returns (string, string, string, uint16, uint8) {
// check param
if (0 == bytes(_num).length) {
return ("", "", "", 0, 0);
}
// check num exist
if (!numExists_[_num]) {
return ("", "", "", 0, 0);
}
return LogisticsDatabase(databaseAddr_).getBrief(_num, _getValidNumName(_num));
}
function getBriefEx(string _num) external view _checkDatabaseAddr returns (string) {
// check param
if (0 == bytes(_num).length) {
return "";
}
// check num exist
if (!numExists_[_num]) {
return "";
}
return LogisticsDatabase(databaseAddr_).getBriefEx(_num, _getValidNumName(_num));
}
function getBriefByIndex(uint _index) external view _checkDatabaseAddr returns (string, string, string, uint16, uint8) {
// check index
// require(numTotalCount_ > _index);
if(numTotalCount_ <= _index) {
return ("", "", "", 0, 0);
}
string memory num = numNames_[_index];
return LogisticsDatabase(databaseAddr_).getBrief(num, _getValidNumName(num));
}
function getBriefExByIndex(uint _index) external view _checkDatabaseAddr returns (string) {
// check index
// require(numTotalCount_ > _index);
if(numTotalCount_ <= _index) {
return ("");
}
string memory num = numNames_[_index];
return LogisticsDatabase(databaseAddr_).getBriefEx(num, _getValidNumName(num));
}
function getBriefElement(string _num, string _tag) external view _checkDatabaseAddr returns (string) {
// check param
if (0 == bytes(_num).length) {
return ("");
}
// check num exist
if (!numExists_[_num]) {
return ("");
}
return LogisticsDatabase(databaseAddr_).getBriefElement(_getValidNumName(_num), _tag);
}
function getBriefElementByIndex(uint _index, string _tag) external view _checkDatabaseAddr returns (string) {
return this.getBriefElement(this.getNumByIndex(_index), _tag);
}
function getBriefInvalid(string _num, uint _invalidIndex) external view _checkDatabaseAddr returns (string, string, string, uint16, uint8) {
// check param
if (0 == bytes(_num).length) {
return ("", "", "", 0, 0);
}
// check invalid index
// require(numInvalidCounts_[_num] > _invalidIndex);
if (numInvalidCounts_[_num] <= _invalidIndex) {
return ("", "", "", 0, 0);
}
// don't need to check num exist
// get invalid num name
string memory invalidNum = _num.concat("-", _invalidIndex.toString());
return LogisticsDatabase(databaseAddr_).getBrief(invalidNum, invalidNum);
}
function getTracksInvalid(string _num, uint _invalidIndex) external view _checkDatabaseAddr returns (string) {
// check param
if (0 == bytes(_num).length) {
return "";
}
// check invalid index
// require(numInvalidCounts_[_num] > _invalidIndex);
if (numInvalidCounts_[_num] <= _invalidIndex) {
return ("");
}
// don't need to check num exist
// find invalid num name
string memory invalidNum = _num.concat("-", _invalidIndex.toString());
return LogisticsDatabase(databaseAddr_).getTracks(invalidNum);
}
function getDatabaseContractAddress() external view _onlyOwner returns (address) {
return databaseAddr_;
}
}
|
update brief from json(similar to) update tracks from json(similar to)
|
function updateEx(string _num, string _info) external _onlyAdminOrHigher {
updateBriefEx(_num, _info);
this.updateTracks(_num, _info, uint8(0));
}
| 12,787,444
|
./partial_match/82/0x1d31Eb94588f362D0A8C9D3B4804aF12B90EC217/sources/flat.sol
|
user events / data types /
|
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external;
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external;
function getGeyserData() external view returns (GeyserData memory geyser);
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index)
external
view
returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index)
external
view
returns (address factory);
function getVaultData(address vault)
external
view
returns (VaultData memory vaultData);
function isValidAddress(address target)
external
view
returns (bool validity);
function isValidVault(address target) external view returns (bool validity);
function getCurrentUnlockedRewards()
external
view
returns (uint256 unlockedRewards);
function getFutureUnlockedRewards(uint256 timestamp)
external
view
returns (uint256 unlockedRewards);
function getCurrentVaultReward(address vault)
external
view
returns (uint256 reward);
function getCurrentStakeReward(address vault, uint256 stakeAmount)
external
view
returns (uint256 reward);
function getFutureVaultReward(address vault, uint256 timestamp)
external
view
returns (uint256 reward);
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view returns (uint256 reward);
function getCurrentVaultStakeUnits(address vault)
external
view
returns (uint256 stakeUnits);
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
external
view
returns (uint256 stakeUnits);
function getCurrentTotalStakeUnits()
external
view
returns (uint256 totalStakeUnits);
function getFutureTotalStakeUnits(uint256 timestamp)
external
view
returns (uint256 totalStakeUnits);
function calculateTotalStakeUnits(
StakeData[] memory stakes,
uint256 timestamp
) external pure returns (uint256 totalStakeUnits);
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) external pure returns (uint256 stakeUnits);
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) external pure returns (uint256 unlockedRewards);
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) external pure returns (RewardOutput memory out);
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) external pure returns (uint256 reward);
}
pragma solidity ^0.8.0;
struct LockData {
address delegate;
address token;
uint256 balance;
}
| 16,895,977
|
pragma solidity ^0.4.24;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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 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 Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts/NectarToken.sol
contract NectarToken is MintableToken {
string public name = "Nectar";
string public symbol = "NCT";
uint8 public decimals = 18;
bool public transfersEnabled = false;
event TransfersEnabled();
// Disable transfers until after the sale
modifier whenTransfersEnabled() {
require(transfersEnabled, "Transfers not enabled");
_;
}
modifier whenTransfersNotEnabled() {
require(!transfersEnabled, "Transfers enabled");
_;
}
function enableTransfers() public onlyOwner whenTransfersNotEnabled {
transfersEnabled = true;
emit TransfersEnabled();
}
function transfer(address to, uint256 value) public whenTransfersEnabled returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenTransfersEnabled returns (bool) {
return super.transferFrom(from, to, value);
}
// Approves and then calls the receiving contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
// Call the receiveApproval function on the contract you want to be notified.
// This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//
// receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//
// It is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
// solium-disable-next-line security/no-low-level-calls, indentation
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))),
msg.sender, _value, this, _extraData), "receiveApproval failed");
return true;
}
}
// File: contracts/OfferMultiSig.sol
contract OfferMultiSig is Pausable {
using SafeMath for uint256;
string public constant NAME = "Offer MultiSig";
string public constant VERSION = "0.0.1";
uint256 public constant MIN_SETTLEMENT_PERIOD = 10;
uint256 public constant MAX_SETTLEMENT_PERIOD = 3600;
event CommunicationsSet(
bytes32 websocketUri
);
event OpenedAgreement(
address _ambassador
);
event CanceledAgreement(
address _ambassador
);
event JoinedAgreement(
address _expert
);
event ClosedAgreement(
address _expert,
address _ambassador
);
event FundsDeposited(
address _ambassador,
address _expert,
uint256 ambassadorBalance,
uint256 expertBalance
);
event StartedSettle(
address initiator,
uint sequence,
uint settlementPeriodEnd
);
event SettleStateChallenged(
address challenger,
uint sequence,
uint settlementPeriodEnd
);
address public nectarAddress; // Address of offer nectar token
address public ambassador; // Address of first channel participant
address public expert; // Address of second channel participant
bool public isOpen = false; // true when both parties have joined
bool public isPending = false; // true when waiting for counterparty to join agreement
uint public settlementPeriodLength; // How long challengers have to reply to settle engagement
uint public isClosed; // if the period has closed
uint public sequence; // state nonce used in during settlement
uint public isInSettlementState; // meta channel is in settling 1: Not settling 0
uint public settlementPeriodEnd; // The time when challenges are no longer accepted after
bytes public state; // the current state
bytes32 public websocketUri; // a geth node running whisper (shh)
constructor(address _nectarAddress, address _ambassador, address _expert, uint _settlementPeriodLength) public {
require(_ambassador != address(0), "No ambassador lib provided to constructor");
require(_expert != address(0), "No expert provided to constructor");
require(_nectarAddress != address(0), "No token provided to constructor");
// solium-disable-next-line indentation
require(_settlementPeriodLength >= MIN_SETTLEMENT_PERIOD && _settlementPeriodLength <= MAX_SETTLEMENT_PERIOD,
"Settlement period out of range");
ambassador = _ambassador;
expert = _expert;
settlementPeriodLength = _settlementPeriodLength;
nectarAddress = _nectarAddress;
}
/** Function only callable by participants */
modifier onlyParticipants() {
require(msg.sender == ambassador || msg.sender == expert, "msg.sender is not a participant");
_;
}
/**
* Function called by ambassador to open channel with _expert
*
* @param _state inital offer state
* @param _v the recovery id from signature of state
* @param _r output of ECDSA signature of state
* @param _s output of ECDSA signature of state
*/
function openAgreement(bytes _state, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused {
// require the channel is not open yet
require(isOpen == false, "openAgreement already called, isOpen true");
require(isPending == false, "openAgreement already called, isPending true");
require(msg.sender == ambassador, "msg.sender is not the ambassador");
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
require(msg.sender == getPartyA(_state), "Party A does not match signature recovery");
// check the account opening a channel signed the initial state
address initiator = getSig(_state, _v, _r, _s);
require(ambassador == initiator, "Initiator in state is not the ambassador");
isPending = true;
state = _state;
open(_state);
emit OpenedAgreement(ambassador);
}
/**
* Function called by ambassador to cancel a channel that hasn't been joined yet
*/
function cancelAgreement() public whenNotPaused {
// require the channel is not open yet
require(isPending == true, "Only a channel in a pending state can be canceled");
require(msg.sender == ambassador, "Only an ambassador can cancel an agreement");
isPending = false;
cancel(nectarAddress);
emit CanceledAgreement(ambassador);
}
/**
* Function called by expert to complete opening the channel with an ambassador defined in the _state
*
* @param _state offer state from ambassador
* @param _v the recovery id from signature of state
* @param _r output of ECDSA signature of state
* @param _s output of ECDSA signature of state
*/
function joinAgreement(bytes _state, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused {
require(isOpen == false, "openAgreement already called, isOpen true");
require(msg.sender == expert, "msg.sender is not the expert");
require(isPending, "Offer not pending");
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
// check that the state is signed by the sender and sender is in the state
address joiningParty = getSig(_state, _v, _r, _s);
require(expert == joiningParty, "Joining party in state is not the expert");
// no longer allow joining functions to be called
isOpen = true;
isPending = false;
join(state);
emit JoinedAgreement(expert);
}
/**
* Function called by ambassador to update balance and add to escrow
* by default to escrows the allowed balance
* @param _state offer state from ambassador
* @param _sigV the recovery id from signature of state by both parties
* @param _sigR output of ECDSA signature of state by both parties
* @param _sigS output of ECDSA signature of state by both parties
* @dev index 0 is the ambassador signature
* @dev index 1 is the expert signature
*/
function depositFunds(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused {
require(isOpen == true, "Tried adding funds to a closed msig wallet");
address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]);
address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]);
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
// Require both signatures
require(_hasAllSigs(_ambassador, _expert), "Missing signatures");
state = _state;
update(_state);
emit FundsDeposited(_ambassador, _expert, getBalanceA(_state), getBalanceB(_state));
}
/**
* Function called by ambassador or expert to close a their channel after a dispute has timedout
*
* @param _state final offer state agreed on by both parties through dispute settlement
* @param _sigV the recovery id from signature of state by both parties
* @param _sigR output of ECDSA signature of state by both parties
* @param _sigS output of ECDSA signature of state by both parties
* @dev index 0 is the ambassador signature
* @dev index 1 is the expert signature
*/
function closeAgreementWithTimeout(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused {
address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]);
address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]);
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
require(settlementPeriodEnd <= block.number, "Settlement period hasn't ended");
require(isClosed == 0, "Offer is closed");
require(isInSettlementState == 1, "Offer is not in settlement state");
require(_hasAllSigs(_ambassador, _expert), "Missing signatures");
require(keccak256(state) == keccak256(_state), "State hash mismatch");
isClosed = 1;
finalize(_state);
isOpen = false;
emit ClosedAgreement(_expert, _ambassador);
}
/**
* Function called by ambassador or expert to close a their channel with close flag
*
* @param _state final offer state agreed on by both parties with close flag
* @param _sigV the recovery id from signature of state by both parties
* @param _sigR output of ECDSA signature of state by both parties
* @param _sigS output of ECDSA signature of state by both parties
* @dev index 0 is the ambassador signature
* @dev index 1 is the expert signature
*/
function closeAgreement(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused {
address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]);
address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]);
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
require(isClosed == 0, "Offer is closed");
/// @dev make sure we're not in dispute
require(isInSettlementState == 0, "Offer is in settlement state");
/// @dev must have close flag
require(_isClosed(_state), "State did not have a signed close out state");
require(_hasAllSigs(_ambassador, _expert), "Missing signatures");
isClosed = 1;
state = _state;
finalize(_state);
isOpen = false;
emit ClosedAgreement(_expert, _ambassador);
}
/**
* Function called by ambassador or expert to start initalize a disputed settlement
* using an agreed upon state. It starts a timeout for a reply using `settlementPeriodLength`
*
* @param _state offer state agreed on by both parties
* @param _sigV the recovery id from signature of state by both parties
* @param _sigR output of ECDSA signature of state by both parties
* @param _sigS output of ECDSA signature of state by both parties
*/
function startSettle(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused {
address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]);
address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]);
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
require(_hasAllSigs(_ambassador, _expert), "Missing signatures");
require(isClosed == 0, "Offer is closed");
require(isInSettlementState == 0, "Offer is in settlement state");
state = _state;
sequence = getSequence(_state);
isInSettlementState = 1;
settlementPeriodEnd = block.number.add(settlementPeriodLength);
emit StartedSettle(msg.sender, sequence, settlementPeriodEnd);
}
/**
* Function called by ambassador or expert to challenge a disputed state
* The new state is accepted if it is signed by both parties and has a higher sequence number
*
* @param _state offer state agreed on by both parties
* @param _sigV the recovery id from signature of state by both parties
* @param _sigR output of ECDSA signature of state by both parties
* @param _sigS output of ECDSA signature of state by both parties
*/
function challengeSettle(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused {
address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]);
address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]);
require(getTokenAddress(_state) == nectarAddress, "Invalid token address");
require(_hasAllSigs(_ambassador, _expert), "Missing signatures");
require(isInSettlementState == 1, "Offer is not in settlement state");
require(block.number < settlementPeriodEnd, "Settlement period has ended");
require(getSequence(_state) > sequence, "Sequence number is too old");
settlementPeriodEnd = block.number.add(settlementPeriodLength);
state = _state;
sequence = getSequence(_state);
emit SettleStateChallenged(msg.sender, sequence, settlementPeriodEnd);
}
/**
* Return when the settlement period is going to end. This is the amount of time
* an ambassor or expert has to reply with a new state
*/
function getSettlementPeriodEnd() public view returns (uint) {
return settlementPeriodEnd;
}
/**
* Function to be called by ambassador to set comunication information
*
* @param _websocketUri uri of whisper node
*/
function setCommunicationUri(bytes32 _websocketUri) external whenNotPaused {
require(msg.sender == ambassador, "msg.sender is not the ambassador");
websocketUri = _websocketUri;
emit CommunicationsSet(websocketUri);
}
/**
* Function called to get the state sequence/nonce
*
* @param _state offer state
*/
function getSequence(bytes _state) public pure returns (uint _seq) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_seq := mload(add(_state, 64))
}
}
function isChannelOpen() public view returns (bool) {
return isOpen;
}
function getWebsocketUri() public view returns (bytes32) {
return websocketUri;
}
/**
* A utility function to check if both parties have signed
*
* @param _a ambassador address
* @param _b expert address
*/
function _hasAllSigs(address _a, address _b) internal view returns (bool) {
require(_a == ambassador && _b == expert, "Signatures do not match parties in state");
return true;
}
/**
* A utility function to check for the closed flag in the offer state
*
* @param _state current offer state
*/
function _isClosed(bytes _state) internal pure returns (bool) {
require(getCloseFlag(_state) == 1, "Offer is not closed");
return true;
}
function getCloseFlag(bytes _state) public pure returns (uint8 _flag) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_flag := mload(add(_state, 32))
}
}
function getPartyA(bytes _state) public pure returns (address _ambassador) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_ambassador := mload(add(_state, 96))
}
}
function getPartyB(bytes _state) public pure returns (address _expert) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_expert := mload(add(_state, 128))
}
}
function getBalanceA(bytes _state) public pure returns (uint256 _balanceA) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_balanceA := mload(add(_state, 192))
}
}
function getBalanceB(bytes _state) public pure returns (uint256 _balanceB) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_balanceB := mload(add(_state, 224))
}
}
function getTokenAddress(bytes _state) public pure returns (address _token) {
// solium-disable-next-line security/no-inline-assembly
assembly {
_token := mload(add(_state, 256))
}
}
function getTotal(bytes _state) public pure returns (uint256) {
uint256 _a = getBalanceA(_state);
uint256 _b = getBalanceB(_state);
return _a.add(_b);
}
function open(bytes _state) internal returns (bool) {
require(msg.sender == getPartyA(_state), "Party A does not match signature recovery");
// get the token instance used to allow funds to msig
NectarToken _t = NectarToken(getTokenAddress(_state));
// ensure the amount sent to open channel matches the signed state balance
require(_t.allowance(getPartyA(_state), this) == getBalanceA(_state), "value does not match ambassador state balance");
// complete the tranfer of ambassador approved tokens
require(_t.transferFrom(getPartyA(_state), this, getBalanceA(_state)), "failed tranfering approved balance from ambassador");
return true;
}
function join(bytes _state) internal view returns (bool) {
// get the token instance used to allow funds to msig
NectarToken _t = NectarToken(getTokenAddress(_state));
// ensure the amount sent to join channel matches the signed state balance
require(msg.sender == getPartyB(_state), "Party B does not match signature recovery");
// Require bonded is the sum of balances in state
require(getTotal(_state) == _t.balanceOf(this), "token total deposited does not match state balance");
return true;
}
function update(bytes _state) internal returns (bool) {
// get the token instance used to allow funds to msig
NectarToken _t = NectarToken(getTokenAddress(_state));
if(_t.allowance(getPartyA(_state), this) > 0) {
require(_t.transferFrom(getPartyA(_state), this, _t.allowance(getPartyA(_state), this)), "failed transfering deposit from party A to contract");
}
require(getTotal(_state) == _t.balanceOf(this), "token total deposited does not match state balance");
}
function cancel(address tokenAddress) internal returns (bool) {
NectarToken _t = NectarToken(tokenAddress);
return _t.transfer(msg.sender, _t.balanceOf(this));
}
/**
* Function called by closeAgreementWithTimeout or closeAgreement to disperse payouts
*
* @param _state final offer state agreed on by both parties with close flag
*/
function finalize(bytes _state) internal returns (bool) {
address _a = getPartyA(_state);
address _b = getPartyB(_state);
NectarToken _t = NectarToken(getTokenAddress(_state));
require(getTotal(_state) == _t.balanceOf(this), "tried finalizing token state that does not match bonded value");
require(_t.transfer(_a, getBalanceA(_state)), "failed transfering balance to party A");
require(_t.transfer(_b, getBalanceB(_state)), "failed transfering balance to party B");
}
/**
* A utility function to return the address of the person that signed the state
*
* @param _state offer state that was signed
* @param _v the recovery id from signature of state by both parties
* @param _r output of ECDSA signature of state by both parties
* @param _s output of ECDSA signature of state by both parties
*/
function getSig(bytes _state, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 h = keccak256(_state);
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h));
address a = ecrecover(prefixedHash, _v, _r, _s);
return a;
}
}
// File: contracts/OfferRegistry.sol
/// @title Creates new Offer Channel contracts and keeps track of them
contract OfferRegistry is Pausable {
struct OfferChannel {
address msig;
address ambassador;
address expert;
}
event InitializedChannel(
address msig,
address ambassador,
address expert,
uint128 guid
);
uint128[] public channelsGuids;
mapping (bytes32 => address) public participantsToChannel;
mapping (uint128 => OfferChannel) public guidToChannel;
address public nectarAddress;
constructor(address _nectarAddress) public {
require(_nectarAddress != address(0), "Invalid token address");
nectarAddress = _nectarAddress;
}
/**
* Function called by ambassador to initialize an offer contract
* It deploys a new offer multi sig and saves it for each participant
*
* @param _ambassador address of ambassador
* @param _expert address of expert
* @param _settlementPeriodLength how long the parties have to dispute the settlement offer channel
*/
function initializeOfferChannel(uint128 guid, address _ambassador, address _expert, uint _settlementPeriodLength) external whenNotPaused {
require(address(0) != _expert, "Invalid expert address");
require(address(0) != _ambassador, "Invalid ambassador address");
require(msg.sender == _ambassador, "Initializer isn't ambassador");
require(guidToChannel[guid].msig == address(0), "GUID already in use");
bytes32 key = getParticipantsHash(_ambassador, _expert);
if (participantsToChannel[key] != address(0)) {
/// @dev check to make sure the participants don't already have an open channel
// solium-disable-next-line indentation
require(OfferMultiSig(participantsToChannel[key]).isChannelOpen() == false,
"Channel already exists between parties");
}
address msig = new OfferMultiSig(nectarAddress, _ambassador, _expert, _settlementPeriodLength);
participantsToChannel[key] = msig;
guidToChannel[guid].msig = msig;
guidToChannel[guid].ambassador = _ambassador;
guidToChannel[guid].expert = _expert;
channelsGuids.push(guid);
emit InitializedChannel(msig, _ambassador, _expert, guid);
}
/**
* Get the total number of offer channels tracked by the contract
*
* @return total number of offer channels
*/
function getNumberOfOffers() external view returns (uint) {
return channelsGuids.length;
}
/**
* Function to get channel participants are on
*
* @param _ambassador the address of ambassador
* @param _expert the address of ambassador
*/
function getParticipantsChannel(address _ambassador, address _expert) external view returns (address) {
bytes32 key = getParticipantsHash(_ambassador, _expert);
require(participantsToChannel[key] != address(0), "Channel does not exist between parties");
return participantsToChannel[key];
}
/**
* Gets all the created channelsGuids
*
* @return list of every channel registered
*/
function getChannelsGuids() external view returns (address[]) {
require(channelsGuids.length != 0, "No channels initialized");
address[] memory registeredChannelsGuids = new address[](channelsGuids.length);
for (uint i = 0; i < channelsGuids.length; i++) {
registeredChannelsGuids[i] = channelsGuids[i];
}
return registeredChannelsGuids;
}
/**
* Pause all channels
*
* @return list of every channel registered
*/
function pauseChannels() external onlyOwner whenNotPaused {
require(channelsGuids.length != 0, "No channels initialized");
pause();
for (uint i = 0; i < channelsGuids.length; i++) {
OfferMultiSig(guidToChannel[channelsGuids[i]].msig).pause();
}
}
/**
* Unpause all channels
*
* @return list of every channel registered
*/
function unpauseChannels() external onlyOwner whenPaused {
require(channelsGuids.length != 0, "No channels initialized");
for (uint i = 0; i < channelsGuids.length; i++) {
OfferMultiSig(guidToChannel[channelsGuids[i]].msig).unpause();
}
}
/**
* Return offer information from state
*
* @return list of every channel registered
* @param _state offer state agreed on by both parties
*/
function getOfferState(
bytes _state
)
public
pure
returns (
bytes32 _guid,
uint256 _nonce,
uint256 _amount,
address _msigAddress,
uint256 _balanceA,
uint256 _balanceB,
address _ambassador,
address _expert,
uint256 _isClosed,
address _token,
uint256 _mask,
uint256 _assertion
)
{
// solium-disable-next-line security/no-inline-assembly
assembly {
_guid := mload(add(_state, 288)) // [256-287] - a globally-unique identifier for the listing
_nonce:= mload(add(_state, 64)) // [32-63] - the sequence of state
_amount := mload(add(_state, 320)) // [288-319] - the offer amount awarded to expert for responses
_msigAddress := mload(add(_state, 160)) // [128-159] - msig address where funds and offer are managed
_balanceA := mload(add(_state,192)) // [160-191] balance in nectar for ambassador
_balanceB := mload(add(_state,224)) // [192-223] balance in nectar for expert
_ambassador := mload(add(_state, 96)) // [64-95] - offer's ambassador address
_expert := mload(add(_state, 128)) // [96-127] - offer's expert address
_isClosed := mload(add(_state, 32)) // [0-31] - 0 or 1 for if the state is marked as closed
_token := mload(add(_state, 256)) // [224-255] - nectar token address
_mask := mload(add(_state, 480)) // [448-479] - assertion mask
_assertion := mload(add(_state, 512)) // [480-511] - assertions from expert
}
}
// Internals
/**
* Utility function to get hash
*
* @param _ambassador address of ambassador
* @param _expert address of expert
* @return hash of ambassador and expert
*/
function getParticipantsHash(address _ambassador, address _expert) internal pure returns (bytes32) {
string memory str_ambassador = toString(_ambassador);
string memory str_expert = toString(_expert);
return keccak256(abi.encodePacked(strConcat(str_ambassador, str_expert)));
}
function toString(address x) internal pure returns (string) {
bytes memory b = new bytes(20);
for (uint i = 0; i < 20; i++) {
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
}
return string(b);
}
function strConcat(string _a, string _b) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory abcde = new string(_ba.length + _bb.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
return string(babcde);
}
/** Disable usage of the fallback function */
function() public payable {
revert("Do not allow sending Eth to this contract");
}
}
|
solium-disable-next-line security/no-inline-assembly
|
function getOfferState(
bytes _state
)
public
pure
returns (
bytes32 _guid,
uint256 _nonce,
uint256 _amount,
address _msigAddress,
uint256 _balanceA,
uint256 _balanceB,
address _ambassador,
address _expert,
uint256 _isClosed,
address _token,
uint256 _mask,
uint256 _assertion
)
{
assembly {
}
}
| 6,495,930
|
pragma solidity ^0.6.12;
abstract contract Context {
function _MSGSENDER157() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA592() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY223() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF306(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER463(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE561(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM21(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER851(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL370(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD799(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB732(a, b, "SafeMath: subtraction overflow");
}
function SUB732(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL950(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV680(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV680(a, b, "SafeMath: division by zero");
}
function DIV680(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD792(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD792(a, b, "SafeMath: modulo by zero");
}
function MOD792(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT333(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE497(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL661(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL661(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL661(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE995(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE621(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE621(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE621(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE995(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE995(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT333(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);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER597(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.TRANSFER463.selector, to, value));
}
function SAFETRANSFERFROM780(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.TRANSFERFROM21.selector, from, to, value));
}
function SAFEAPPROVE352(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE696(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, value));
}
function SAFEINCREASEALLOWANCE57(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD799(value);
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE5(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB732(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN182(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. 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).FUNCTIONCALL661(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");
}
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED950(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER157();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED950(address(0), msgSender);
}
function OWNER835() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER465() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER157(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP697() public virtual ONLYOWNER465 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED950(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP738(address newOwner) public virtual ONLYOWNER465 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED950(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME734() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL830() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS862() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY223() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF306(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER463(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER846(_MSGSENDER157(), recipient, amount);
return true;
}
function ALLOWANCE696(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE561(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE805(_MSGSENDER157(), spender, amount);
return true;
}
function TRANSFERFROM21(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER846(sender, recipient, amount);
_APPROVE805(sender, _MSGSENDER157(), _allowances[sender][_MSGSENDER157()].SUB732(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE200(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE805(_MSGSENDER157(), spender, _allowances[_MSGSENDER157()][spender].ADD799(addedValue));
return true;
}
function DECREASEALLOWANCE585(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE805(_MSGSENDER157(), spender, _allowances[_MSGSENDER157()][spender].SUB732(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER846(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER151(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB732(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD799(amount);
emit TRANSFER851(sender, recipient, amount);
}
function _MINT127(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER151(address(0), account, amount);
_totalSupply = _totalSupply.ADD799(amount);
_balances[account] = _balances[account].ADD799(amount);
emit TRANSFER851(address(0), account, amount);
}
function _BURN291(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER151(account, address(0), amount);
_balances[account] = _balances[account].SUB732(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB732(amount);
emit TRANSFER851(account, address(0), amount);
}
function _APPROVE805(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL370(owner, spender, amount);
}
function _SETUPDECIMALS256(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER151(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
//nGASToken
contract nGASToken is ERC20("pumpgasplatform.com", "nGAS"), Ownable {
function MINT597(address _to, uint256 _amount) public ONLYOWNER465 { //inject NONSTANDARD NAMING
_MINT127(_to, _amount);
}
function TRANSFER463(address to, uint256 amount) public override returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER463(to, _PARTIALBURN883(msg.sender, amount));
}
function TRANSFERFROM21(address from, address to, uint256 amount) public override returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM21(from, to, _PARTIALBURN883(from, amount));
}
function _PARTIALBURN883(address sender, uint256 amount) internal returns (uint256) { //inject NONSTANDARD NAMING
uint256 burnAmount = (amount.MUL950(30)).DIV680(1000); //3% will be burned every tx
if (burnAmount > 0) {
_BURN291(sender, burnAmount);
}
return amount.SUB732(burnAmount);
}
}
|
inject NONSTANDARD NAMING
|
function OWNER835() public view returns (address) {
| 1,839,183
|
./partial_match/1/0xF708005ceE17b2c5Fe1a01591E32ad6183A12EaE/sources/@yield-protocol/utils-v2/contracts/token/ERC20Rewards.sol
|
Claim all rewards from caller into a given address
|
function claim(address to)
external
returns (uint256 claiming)
{
claiming = _claim(msg.sender, to);
}
| 2,802,722
|
./partial_match/3/0x0289bfEEcc884Fd71cb123D72Df76Fa90664D24a/sources/UniswapLocked.sol
|
/ solhint-disable-next-line not-rely-on-time
|
function releaseETH() public {
require(block.timestamp >= _releaseTime, "UniswapLocked: current time is before release time");
require(address(this).balance > 0, "UniswapLocked: no Eth to release");
payable(owner()).transfer(address(this).balance);
}
| 5,125,560
|
./partial_match/1/0x262edD66a0B2D7e4411dbd9484A1e01B6F701045/sources/GLDPEPE.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(router), tokenAmount);
address(this),
tokenAmount,
address(marketingWallet),
block.timestamp
);
}
| 2,708,371
|
//
// compiler: 0.4.21+commit.dfe3193c.Emscripten.clang
//
pragma solidity ^0.4.21;
contract owned {
address public owner;
function owned() public { owner = msg.sender; }
function changeOwner( address newowner ) public onlyOwner {owner = newowner;}
function closedown() public onlyOwner { selfdestruct( owner ); }
modifier onlyOwner {
if (msg.sender != owner) { revert(); }
_;
}
}
// token expected to be at least ERC20-compliant
interface ERC20 {
function decimals() external returns (uint8);
function transfer(address to, uint256 value) external;
function balanceOf( address owner ) external returns (uint);
}
contract ICO is owned {
ERC20 public tokenSC; // token this ICO is selling
address treasury; // [optional] where to direct incoming Ether
uint public start; // seconds since Jan 1 1970 GMT
uint public duration; // seconds
uint public tokpereth; // price : NOTE: take care regarding decimal units
// If treasury has a value then all payments will automatically be sent there
function ICO( address _erc20,
address _treasury,
uint _startSec,
uint _durationSec,
uint _tokpereth ) public {
require( isContract(_erc20) );
require( _tokpereth > 0 );
if (_treasury != address(0))
require( isContract(_treasury) );
tokenSC = ERC20( _erc20 );
treasury = _treasury;
start = _startSec;
duration = _durationSec;
tokpereth = _tokpereth;
}
function() public payable {
if (now < start || now > (start + duration))
revert();
// quantity =
// amountinwei * tokpereth/weipereth * (bonus+100)/100
// = amountinwei * tokpereth/1e18 * (bonus+100)/100
// = msg.value * tokpereth/1e20 * (bonus+100)
uint qty =
multiply( divide( multiply( msg.value,
tokpereth ),
1e20),
(bonus()+100) );
// the above is in units of tokens - multiply by 10**decimals to work out
// the number of units to transfer
qty = multiply( qty, 10**(uint(tokenSC.decimals())) );
if (qty > tokenSC.balanceOf(address(this)) || qty < 1)
revert();
tokenSC.transfer( msg.sender, qty );
if (treasury != address(0)) treasury.transfer( msg.value );
}
// unsold tokens can be claimed by owner after sale ends
function claimUnsold() public onlyOwner {
if ( now < (start + duration) )
revert();
tokenSC.transfer( owner, tokenSC.balanceOf(address(this)) );
}
function withdraw( uint amount ) public onlyOwner returns (bool) {
require (amount <= address(this).balance);
return owner.send( amount );
}
function bonus() public view returns(uint) {
uint elapsed = now - start;
if (elapsed < 48 hours) return 50;
if (elapsed < 2 weeks) return 20;
if (elapsed < 3 weeks) return 10;
if (elapsed < 4 weeks) return 5;
return 0;
}
function isContract( address _a ) internal view returns (bool) {
uint ecs;
assembly { ecs := extcodesize(_a) }
return ecs > 0;
}
// ref: github.com/OpenZeppelin/zeppelin-solidity/
// blob/master/contracts/math/SafeMath.sol
function multiply(uint256 a, uint256 b) pure private returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function divide(uint256 a, uint256 b) pure private returns (uint256) {
return a / b;
}
}
|
unsold tokens can be claimed by owner after sale ends
|
function claimUnsold() public onlyOwner {
if ( now < (start + duration) )
revert();
tokenSC.transfer( owner, tokenSC.balanceOf(address(this)) );
}
| 5,494,479
|
./full_match/73799/0x8eCDD1392257A86b9eb297554c6Abe3FaF97AbEe/sources/contracts/dependencies/MetaToken.sol
|
claimMetaTokenFor - Claims a meta token on the behalf of the owner This function can only be called by an enrolled claimer This function reverts if the meta token is already retired tokenID - ID of the meta token to be claimed amount - amount of meta tokens to be claimed owner - address of the owner of the meta token/
|
function claimMetaTokenFor(
uint256 tokenID,
uint256 amount,
address owner
) external onlyAdmin {
_claimMetaTokenFor(tokenID, amount, owner);
}
| 16,362,628
|
./full_match/42161/0xa0Dd926Fb5840f6A1B1C5315306894508144faF3/sources/project:/contracts/utils/Permissioned.sol
|
Remove oneself from the owner role.
|
function renounceOwner()
public virtual
{
renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
| 16,301,464
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/**
* @title A subscription contract allowing publishers to create subscription plans and users to subscribe to these plans, renew, pause or cancel their subscriptions.
* @author PA. Oliva
* @custom:experimental This is an experimental contract.
*/
contract Subscriptions is Ownable, Pausable{
/* State variables */
struct Plan {
address payable publisher;
uint fee;
uint duration;
}
struct Subscription {
address subscriber;
uint startDate;
uint endDate;
uint pauseDate;
}
mapping(address => mapping(uint => Subscription)) public subscriptions; // (subscriber -> (planId -> Subscription))
mapping(uint => Plan) public plans; // (planId -> Plan)
uint public nextPlanId;
/* Events - publicize actions to external listeners */
/**
* @notice Log: `publisher` created plan `planId` by `publisher` at time `timestamp`
* @param publisher Publisher address
* @param planId Plan ID
* @param timestamp Block timestamp
*/
event PlanCreated(address publisher, uint planId, uint timestamp);
/**
* @notice Log: `subscriber` subscribed to plan `planId` at time `timestamp`
* @param subscriber Subscriber address
* @param planId Plan ID
* @param timestamp Block timestamp
*/
event Subscribed(address subscriber, uint planId, uint timestamp);
/**
* @notice Log: `subscriber` cancelled subscription to `planId` at time `timestamp`
* @param subscriber Subscriber address
* @param planId Plan ID
* @param timestamp Block timestamp
*/
event CancelledSubscription(address subscriber, uint planId, uint timestamp);
/**
* @notice Log: `subscriber` renewed subscription to `planId` at time `timestamp`
* @param subscriber Subscriber address
* @param planId Plan ID
* @param timestamp Block timestamp
*/
event RenewedSubscription(address subscriber, uint planId, uint timestamp);
/**
* @notice Log: `subscriber` paused subscription to `planId` at time `timestamp`
* @param subscriber Subscriber address
* @param planId Plan ID
* @param timestamp Block timestamp
*/
event PausedSubscription(address subscriber, uint planId, uint timestamp);
/**
* @notice Log: `subscriber` unpaused subscription to `planId` at time `timestamp`
* @param subscriber Subscriber address
* @param planId Plan ID
* @param timestamp Block timestamp
*/
event UnpausedSubscription(address subscriber, uint planId, uint timestamp);
/* Modifiers */
/**
* @notice Require that the plan `planId` exists
* @param planId Plan ID
*/
modifier planExists(uint planId){
require(
planId < nextPlanId,
"Plan does not exist"
);
_;
}
/**
* @notice Require that msg.sender has subscribed to Plan `planId`
* @param planId Plan ID
*/
modifier hasSubscribed(uint planId) {
require(
subscriptions[msg.sender][planId].subscriber == msg.sender,
"Has not subscribed yet"
);
_;
}
/**
* @notice Require that msg.sender has an active subscription to Plan `planId`
* @param planId Plan ID
*/
modifier hasActiveSubscription(uint planId) {
Subscription storage sub = subscriptions[msg.sender][planId];
require(
sub.subscriber == msg.sender,
"Has not subscribed yet"
);
require(
sub.pauseDate == 0,
"Subscription is not active"
);
_;
}
/**
* @notice Require that msg.sender has a paused subscription to Plan `planId`
* @param planId Plan ID
*/
modifier hasPausedSubscription(uint planId) {
Subscription storage sub = subscriptions[msg.sender][planId];
require(
sub.subscriber == msg.sender,
"Has not subscribed yet"
);
require(
sub.pauseDate > 0,
"Subscription is not active"
);
_;
}
/**
* @notice Require that subscription has not expired
* @param planId Plan ID
*/
modifier hasNotExpired(uint planId) {
Subscription storage sub = subscriptions[msg.sender][planId];
require(
sub.endDate > block.timestamp,
"Subscription has expired"
);
_;
}
/**
* @notice Require that msg.sender has not subscribed yet to Plan `planId`
* @param planId Plan ID
*/
modifier hasNotSubscribed(uint planId) {
require(
subscriptions[msg.sender][planId].subscriber == address(0),
"Has already subscribed"
);
_;
}
/* Functions */
/**
* @notice Pause the contract if unpaused
*
* Requirements:
* - Only from owner
*/
function pauseContract() public onlyOwner() {
super._pause();
}
/**
* @notice Unpause the contract if paused
*
* Requirements:
* - Only from owner
*/
function unpauseContract() public onlyOwner() {
super._unpause();
}
/**
* @notice Create a new plan with fee `fee` and duration `durationDays`
* @dev Emit PlanCreated
* @param fee Subscription fee in gwei
* @param durationDays Subscription term in days
* @return ID of plan newly created
*/
function createPlan(uint fee, uint durationDays) public returns (uint){
require(durationDays > 0);
uint id = nextPlanId;
plans[id] = Plan({
publisher: payable(msg.sender),
fee: fee,
duration: durationDays * 1 days
});
emit PlanCreated(msg.sender, id, block.timestamp);
nextPlanId += 1;
return id;
}
/**
* @notice Subscribe to plan `planId`
* @dev Emit Subscribed
* @param planId Plan ID to subscribe to
* @return ID of plan subscribed to
*
* Requirements:
* - The plan exists
* - Msg sender has not subscribed to it yet
*/
function subscribe(uint planId) public payable planExists(planId) hasNotSubscribed(planId) whenNotPaused() returns (uint){
Plan storage plan = plans[planId];
// Register the subscription
subscriptions[msg.sender][planId] = Subscription({
subscriber: msg.sender,
startDate: block.timestamp,
endDate: block.timestamp + plan.duration,
pauseDate: 0
});
// Transfer fee to the publisher
(bool success, ) = plan.publisher.call{value: plan.fee}("");
require(success, "Transfer failed.");
// Emit log
emit Subscribed(msg.sender, planId, block.timestamp);
return planId;
}
/**
* @notice Cancel subscription to plan `planId`
* @dev Emit CancelledSubscription
* @param planId Plan ID to subscribe to
* @return Plan ID whose subscription is cancelled
*
* Requirements:
* - Msg sender has a subscription to the plan
*/
function cancelSubscription(uint planId) public hasSubscribed(planId) returns (uint){
// Require that subscriber has subscribed to this plan already
require(subscriptions[msg.sender][planId].subscriber == msg.sender);
// Delete the subscription
delete subscriptions[msg.sender][planId];
emit CancelledSubscription(msg.sender, planId, block.timestamp);
return planId;
}
/**
* @notice Renew subscription to plan `planId`
* @param planId Plan ID to renew subcription for
* @return Subscription new end date
*
* Requirements:
* - Msg sender has an active subscription to the plan
*/
function renewSubscription(uint planId) public payable hasActiveSubscription(planId) whenNotPaused() returns(uint){
// Renew subscription with startDate = max(block.timestamp, endDate)
Plan storage plan = plans[planId];
Subscription storage subscription = subscriptions[msg.sender][planId];
// Renew or extend subscription by plan duration
subscription.startDate = block.timestamp;
subscription.endDate = Math.max(block.timestamp, subscription.endDate) + plan.duration;
// Transfer fee to publisher
(bool success, ) = plan.publisher.call{value: plan.fee}("");
require(success, "Transfer failed.");
emit RenewedSubscription(msg.sender, planId, subscription.startDate);
return subscription.endDate;
}
/**
* @notice Pause subscription to plan `planId`
* @param planId Plan ID to pause subcription for
* @return Subscription pause date
*
* Requirements:
* - Msg sender has an active subscription to the plan
* - The subscription has not expired
*/
function pauseSubscription(uint planId) public payable hasActiveSubscription(planId) hasNotExpired(planId) returns(uint){
Subscription storage subscription = subscriptions[msg.sender][planId];
subscription.pauseDate = block.timestamp;
emit PausedSubscription(msg.sender, planId, subscription.pauseDate);
return subscription.pauseDate;
}
/**
* @notice Unpause subscription to plan `planId`
* @dev This pushes the subscription end date back by the duration of the pause
* @param planId Plan ID to pause subcription for
* @return Subscription new end date
*
* Requirements:
* - Msg sender has a paused subscription to the plan
*/
function unpauseSubscription(uint planId) public payable hasPausedSubscription(planId) returns(uint){
Subscription storage subscription = subscriptions[msg.sender][planId];
subscription.endDate = subscription.endDate + (block.timestamp - subscription.pauseDate);
subscription.pauseDate = 0;
emit UnpausedSubscription(msg.sender, planId, subscription.pauseDate);
return subscription.endDate;
}
}
|
Functions / Pause the contract if unpaused Requirements: - Only from owner/
|
function pauseContract() public onlyOwner() {
super._pause();
}
| 2,541,160
|
pragma solidity ^0.5.10;
/** @title BitcoinSPV */
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
// The target at minimum Difficulty. Also the target of the genesis block
uint256 public constant DIFF1_TARGET =
0xffff0000000000000000000000000000000000000000000000000000;
uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds
uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag)
internal
pure
returns (uint8)
{
if (uint8(_flag[0]) == 0xff) {
return 8; // one-byte flag, 8 bytes data
}
if (uint8(_flag[0]) == 0xfe) {
return 4; // one-byte flag, 4 bytes data
}
if (uint8(_flag[0]) == 0xfd) {
return 2; // one-byte flag, 2 bytes data
}
return 0; // flag is data
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b)
internal
pure
returns (bytes memory)
{
bytes memory _newValue = new bytes(_b.length);
for (uint256 i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
/// @notice Changes the endianness of a uint256
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
/// @param _b The unsigned integer to reverse
/// @return The reversed value
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v =
((v >> 8) &
0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v &
0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) <<
8);
// swap 2-byte long pairs
v =
((v >> 16) &
0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v &
0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) <<
16);
// swap 4-byte long pairs
v =
((v >> 32) &
0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v &
0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) <<
32);
// swap 8-byte long pairs
v =
((v >> 64) &
0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v &
0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) <<
64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/// @notice Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
uint256 _number;
for (uint256 i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2**(8 * (_b.length - (i + 1))));
}
return _number;
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num)
internal
pure
returns (bytes memory)
{
uint256 _start = _b.length.sub(_num);
return _b.slice(_start, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) internal pure returns (bytes memory) {
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) internal pure returns (bytes32) {
return
abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).toBytes32();
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The pre-image
/// @return The digest
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
assembly {
let ptr := mload(0x40)
pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32))
pop(staticcall(gas, 2, ptr, 32, ptr, 32))
res := mload(ptr)
}
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint8 _index)
internal
pure
returns (bytes memory)
{
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i++) {
_remaining = _vin.slice(_offset, _vin.length - _offset);
_len = determineInputLength(_remaining);
_offset = _offset + _len;
}
_remaining = _vin.slice(_offset, _vin.length - _offset);
_len = determineInputLength(_remaining);
return _vin.slice(_offset, _len);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) internal pure returns (bool) {
return _input.keccak256Slice(36, 1) != keccak256(hex"00");
}
/// @notice Determines the length of an input from its scriptsig
/// @dev 36 for outpoint, 1 for scriptsig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input)
internal
pure
returns (uint256)
{
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input)
internal
pure
returns (bytes memory)
{
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input)
internal
pure
returns (uint32)
{
bytes memory _leSeqence = extractSequenceLELegacy(_input);
bytes memory _beSequence = reverseEndianness(_leSeqence);
return uint32(bytesToUint(_beSequence));
}
/// @notice Extracts the VarInt-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended script sig
function extractScriptSig(bytes memory _input)
internal
pure
returns (bytes memory)
{
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input)
internal
pure
returns (uint8, uint256)
{
bytes memory _varIntTag = _input.slice(36, 1);
uint8 _varIntDataLen = determineVarIntDataLength(_varIntTag);
uint256 _len;
if (_varIntDataLen == 0) {
_len = uint8(_varIntTag[0]);
} else {
_len = bytesToUint(
reverseEndianness(_input.slice(36 + 1, _varIntDataLen))
);
}
return (_varIntDataLen, _len);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input)
internal
pure
returns (bytes memory)
{
return _input.slice(37, 4);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input)
internal
pure
returns (uint32)
{
bytes memory _leSeqence = extractSequenceLEWitness(_input);
bytes memory _inputeSequence = reverseEndianness(_leSeqence);
return uint32(bytesToUint(_inputeSequence));
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32 byte tx id with 4 byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input)
internal
pure
returns (bytes memory)
{
return _input.slice(0, 36);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32 byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input)
internal
pure
returns (bytes32)
{
return _input.slice(0, 32).toBytes32();
}
/// @notice Extracts the outpoint index from an input
/// @dev 32 byte tx id
/// @param _input The input
/// @return The tx id (big-endian bytes)
function extractInputTxId(bytes memory _input)
internal
pure
returns (bytes32)
{
bytes memory _leId = abi.encodePacked(extractInputTxIdLE(_input));
bytes memory _beId = reverseEndianness(_leId);
return _beId.toBytes32();
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4 byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input)
internal
pure
returns (bytes memory)
{
return _input.slice(32, 4);
}
/// @notice Extracts the tx input index from the input in a tx
/// @dev 4 byte tx index
/// @param _input The input
/// @return The tx index (big-endian uint)
function extractTxIndex(bytes memory _input)
internal
pure
returns (uint32)
{
bytes memory _leIndex = extractTxIndexLE(_input);
bytes memory _beIndex = reverseEndianness(_leIndex);
return uint32(bytesToUint(_beIndex));
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev 5 types: WPKH, WSH, PKH, SH, and OP_RETURN
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output)
internal
pure
returns (uint256)
{
uint8 _len = uint8(_output.slice(8, 1)[0]);
require(_len < 0xfd, "Multi-byte VarInts not supported");
return _len + 8 + 1; // 8 byte value, 1 byte for _len itself
}
/// @notice Extracts the output at a given index in the TxIns vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint8 _index)
internal
pure
returns (bytes memory)
{
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i++) {
_remaining = _vout.slice(_offset, _vout.length - _offset);
_len = determineOutputLength(_remaining);
_offset = _offset + _len;
}
_remaining = _vout.slice(_offset, _vout.length - _offset);
_len = determineOutputLength(_remaining);
return _vout.slice(_offset, _len);
}
/// @notice Extracts the output script length
/// @dev Indexes the length prefix on the pk_script
/// @param _output The output
/// @return The 1 byte length prefix
function extractOutputScriptLen(bytes memory _output)
internal
pure
returns (bytes memory)
{
return _output.slice(8, 1);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output)
internal
pure
returns (bytes memory)
{
return _output.slice(0, 8);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) internal pure returns (uint64) {
bytes memory _leValue = extractValueLE(_output);
bytes memory _beValue = reverseEndianness(_leValue);
return uint64(bytesToUint(_beValue));
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output)
internal
pure
returns (bytes memory)
{
if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) {
return hex"";
}
bytes memory _dataLen = _output.slice(10, 1);
return _output.slice(11, bytesToUint(_dataLen));
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The output
/// @return The hash committed to by the pk_script, or null for errors
function extractHash(bytes memory _output)
internal
pure
returns (bytes memory)
{
if (uint8(_output.slice(9, 1)[0]) == 0) {
uint256 _len = uint8(extractOutputScriptLen(_output)[0]) - 2;
// Check for maliciously formatted witness outputs
if (uint8(_output.slice(10, 1)[0]) != uint8(_len)) {
return hex"";
}
return _output.slice(11, _len);
} else {
bytes32 _tag = _output.keccak256Slice(8, 3);
// p2pkh
if (_tag == keccak256(hex"1976a9")) {
// Check for maliciously formatted p2pkh
if (
uint8(_output.slice(11, 1)[0]) != 0x14 ||
_output.keccak256Slice(_output.length - 2, 2) !=
keccak256(hex"88ac")
) {
return hex"";
}
return _output.slice(12, 20);
//p2sh
} else if (_tag == keccak256(hex"17a914")) {
// Check for maliciously formatted p2sh
if (uint8(_output.slice(_output.length - 1, 1)[0]) != 0x87) {
return hex"";
}
return _output.slice(11, 20);
}
}
return hex""; /* NB: will trigger on OPRETURN and non-standard that don't overrun */
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) internal pure returns (bool) {
uint256 _offset = 1;
uint8 _nIns = uint8(_vin.slice(0, 1)[0]);
// Not valid if it says there are too many or no inputs
if (_nIns >= 0xfd || _nIns == 0) {
return false;
}
for (uint8 i = 0; i < _nIns; i++) {
// Grab the next input and determine its length.
// Increase the offset by that much
_offset += determineInputLength(
_vin.slice(_offset, _vin.length - _offset)
);
// Returns false we jump past the end
if (_offset > _vin.length) {
return false;
}
}
// Returns false if we're not exactly at the end
return _offset == _vin.length;
}
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted bout
function validateVout(bytes memory _vout) internal pure returns (bool) {
uint256 _offset = 1;
uint8 _nOuts = uint8(_vout.slice(0, 1)[0]);
// Not valid if it says there are too many or no inputs
if (_nOuts >= 0xfd || _nOuts == 0) {
return false;
}
for (uint8 i = 0; i < _nOuts; i++) {
// Grab the next input and determine its length.
// Increase the offset by that much
_offset += determineOutputLength(
_vout.slice(_offset, _vout.length - _offset)
);
// Returns false we jump past the end
if (_offset > _vout.length) {
return false;
}
}
// Returns false if we're not exactly at the end
return _offset == _vout.length;
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header)
internal
pure
returns (bytes memory)
{
return _header.slice(36, 32);
}
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (big-endian)
function extractMerkleRootBE(bytes memory _header)
internal
pure
returns (bytes memory)
{
return reverseEndianness(extractMerkleRootLE(_header));
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header)
internal
pure
returns (uint256)
{
bytes memory _m = _header.slice(72, 3);
uint8 _e = uint8(_header[75]);
uint256 _mantissa = bytesToUint(reverseEndianness(_m));
uint256 _exponent = _e - 3;
return _mantissa * (256**_exponent);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target)
internal
pure
returns (uint256)
{
// Difficulty 1 calculated from 0x1d00ffff
return DIFF1_TARGET.div(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header)
internal
pure
returns (bytes memory)
{
return _header.slice(4, 32);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (big-endian)
function extractPrevBlockBE(bytes memory _header)
internal
pure
returns (bytes memory)
{
return reverseEndianness(extractPrevBlockLE(_header));
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header)
internal
pure
returns (bytes memory)
{
return _header.slice(68, 4);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header)
internal
pure
returns (uint32)
{
return
uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header))));
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header)
internal
pure
returns (uint256)
{
return calculateDifficulty(extractTarget(_header));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b)
internal
pure
returns (bytes32)
{
return hash256(abi.encodePacked(_a, _b));
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint256 _index)
internal
pure
returns (bool)
{
// Not an even number of hashes
if (_proof.length % 32 != 0) {
return false;
}
// Special case for coinbase-only blocks
if (_proof.length == 32) {
return true;
}
// Should never occur
if (_proof.length == 64) {
return false;
}
uint256 _idx = _index;
bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32();
bytes32 _current = _proof.slice(0, 32).toBytes32();
for (uint256 i = 1; i < (_proof.length.div(32)) - 1; i++) {
if (_idx % 2 == 1) {
_current = _hash256MerkleStep(
_proof.slice(i * 32, 32),
abi.encodePacked(_current)
);
} else {
_current = _hash256MerkleStep(
abi.encodePacked(_current),
_proof.slice(i * 32, 32)
);
}
_idx = _idx >> 1;
}
return _current == _root;
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);
// Normalize ratio to factor of 4 if very long or very short
if (_elapsedTime < RETARGET_PERIOD.div(4)) {
_elapsedTime = RETARGET_PERIOD.div(4);
}
if (_elapsedTime > RETARGET_PERIOD.mul(4)) {
_elapsedTime = RETARGET_PERIOD.mul(4);
}
/*
NB: high targets e.g. ffff0020 can cause overflows here
so we divide it by 256**2, then multiply by 256**2 later
we know the target is evenly divisible by 256**2, so this isn't an issue
*/
uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);
return _adjusted.div(RETARGET_PERIOD).mul(65536);
}
}
|
Extracts the tx input index from the input in a tx 4 byte tx index _input The input return The tx index (big-endian uint)
|
function extractTxIndex(bytes memory _input)
internal
pure
returns (uint32)
{
bytes memory _leIndex = extractTxIndexLE(_input);
bytes memory _beIndex = reverseEndianness(_leIndex);
return uint32(bytesToUint(_beIndex));
}
| 5,491,216
|
/*6.7L Power Stroke Turbo Diesel V8 - liquidity generator magic*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import { Ownable, SafeMath } from '/interfaces/CommonImports.sol';
import { IERC20Burnable } from '/interfaces/IERC20Burnable.sol';
import '/UniswapV2/IUniswapV2Router02.sol';
import '/interfaces/IBalancer.sol';
interface IFreeFromUpTo {
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
contract V8TurboDiesel is Ownable, IBalancer {
using SafeMath for uint256;
address internal UniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address payable public override treasury;
IERC20Burnable token;
IUniswapV2Router02 routerInterface = IUniswapV2Router02(UniRouter);
address internal WETH = routerInterface.WETH();
constructor() public {
treasury = msg.sender;
}
function setToken(address tokenAddr) public onlyOwner {
token = IERC20Burnable(tokenAddr);
}
function setTreasury(address treasuryN) external override{
require(msg.sender == address(token), "only token");
treasury = payable(treasuryN);
}
receive () external payable {}
/** Path stuff **/
function getPath(address tokent,bool isSell) internal view returns (address[] memory path){
path = new address[](2);
path[0] = isSell ? tokent : WETH;
path[1] = isSell ? WETH : tokent;
return path;
}
function getSellPath(address tokent) public view returns (address[] memory path) {
path = getPath(tokent,true);
}
function getBuyPath(address tokent) public view returns (address[] memory path){
path = getPath(tokent,false);
}
/** Path stuff end **/
function rebalance(address rewardRecp) external override returns (uint256) {
require(msg.sender == address(token), "only token");
swapEthForTokens();
uint256 lockableBalance = token.balanceOf(address(this));
uint256 callerReward = token.getCallerCut(lockableBalance);
token.transfer(rewardRecp, callerReward);
token.burn(lockableBalance.sub(callerReward,"Underflow on burn"));
return lockableBalance.sub(callerReward,"underflow on return");
}
function swapEthForTokens() private {
uint256 treasuryAmount = token.getCallerCut(address(this).balance);
(bool success,) = treasury.call{value: treasuryAmount}("");
require(success,"treasury send failed");
routerInterface.swapExactETHForTokensSupportingFeeOnTransferTokens{value: address(this).balance}(
0,
getBuyPath(address(token)),
address(this),
block.timestamp.add(200) + 10 minutes
);
}
function swapTokensForETH(uint256 tokenAmount) private {
//Approve before swap
token.approve(UniRouter,tokenAmount);
routerInterface.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
getSellPath(address(token)),
address(this),
block.timestamp.add(200) + 20 minutes
);
}
function addLiq(uint256 tokenAmount,uint256 ethamount) private {
//Approve before adding liq
token.approve(UniRouter,tokenAmount);
routerInterface.addLiquidityETH{value:ethamount}(
address(token),
tokenAmount,
0,
ethamount.div(2),//Atleast half of eth should be added
address(token),
block.timestamp.add(200) + 25 minutes
);
}
function AddLiq() external override returns (bool) {
//Sell half of the amount to ETH
uint256 tokenAmount = token.balanceOf(address(this)).div(2);
//Swap half of it to eth
swapTokensForETH(tokenAmount);
//Add liq with remaining eth and tokens
addLiq(token.balanceOf(address(this)),address(this).balance);
//If any eth remains swap to token
if(address(this).balance > 0)
swapEthForTokens();
return true;
}
}
|
Sell half of the amount to ETHSwap half of it to ethAdd liq with remaining eth and tokensIf any eth remains swap to token
|
function AddLiq() external override returns (bool) {
uint256 tokenAmount = token.balanceOf(address(this)).div(2);
swapTokensForETH(tokenAmount);
addLiq(token.balanceOf(address(this)),address(this).balance);
if(address(this).balance > 0)
swapEthForTokens();
return true;
}
| 13,073,835
|
pragma solidity ^0.4.24;
//Swap Deployer functions - descriptions can be found in Deployer.sol
interface Deployer_Interface {
function newContract(address _party, address user_contract, uint _start_date) external payable returns (address);
}
//Slightly modified SafeMath library - includes a min function
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint a, uint b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
//Swap factory functions - descriptions can be found in Factory.sol
interface Factory_Interface {
function createToken(uint _supply, address _party, uint _start_date) external returns (address,address, uint);
function payToken(address _party, address _token_add) external;
function deployContract(uint _start_date) external payable returns (address);
function getBase() external view returns(address);
function getVariables() external view returns (address, uint, uint, address,uint);
function isWhitelisted(address _member) external view returns (bool);
}
/**
*The DRCTLibrary contains the reference code used in the DRCT_Token (an ERC20 compliant token
*representing the payout of the swap contract specified in the Factory contract).
*/
library DRCTLibrary{
using SafeMath for uint256;
/*Structs*/
/**
*@dev Keeps track of balance amounts in the balances array
*/
struct Balance {
address owner;
uint amount;
}
struct TokenStorage{
//This is the factory contract that the token is standardized at
address factory_contract;
//Total supply of outstanding tokens in the contract
uint total_supply;
//Mapping from: swap address -> user balance struct (index for a particular user's balance can be found in swap_balances_index)
mapping(address => Balance[]) swap_balances;
//Mapping from: swap address -> user -> swap_balances index
mapping(address => mapping(address => uint)) swap_balances_index;
//Mapping from: user -> dynamic array of swap addresses (index for a particular swap can be found in user_swaps_index)
mapping(address => address[]) user_swaps;
//Mapping from: user -> swap address -> user_swaps index
mapping(address => mapping(address => uint)) user_swaps_index;
//Mapping from: user -> total balance accross all entered swaps
mapping(address => uint) user_total_balances;
//Mapping from: owner -> spender -> amount allowed
mapping(address => mapping(address => uint)) allowed;
}
/*Events*/
/**
*@dev events for transfer and approvals
*/
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event CreateToken(address _from, uint _value);
/*Functions*/
/**
*@dev Constructor - sets values for token name and token supply, as well as the
*factory_contract, the swap.
*@param _factory
*/
function startToken(TokenStorage storage self,address _factory) public {
self.factory_contract = _factory;
}
/**
*@dev ensures the member is whitelisted
*@param _member is the member address that is chekced agaist the whitelist
*/
function isWhitelisted(TokenStorage storage self,address _member) internal view returns(bool){
Factory_Interface _factory = Factory_Interface(self.factory_contract);
return _factory.isWhitelisted(_member);
}
/**
*@dev gets the factory address
*/
function getFactoryAddress(TokenStorage storage self) external view returns(address){
return self.factory_contract;
}
/**
*@dev Token Creator - This function is called by the factory contract and creates new tokens
*for the user
*@param _supply amount of DRCT tokens created by the factory contract for this swap
*@param _owner address
*@param _swap address
*/
function createToken(TokenStorage storage self,uint _supply, address _owner, address _swap) public{
require(msg.sender == self.factory_contract);
//Update total supply of DRCT Tokens
self.total_supply = self.total_supply.add(_supply);
//Update the total balance of the owner
self.user_total_balances[_owner] = self.user_total_balances[_owner].add(_supply);
//If the user has not entered any swaps already, push a zeroed address to their user_swaps mapping to prevent default value conflicts in user_swaps_index
if (self.user_swaps[_owner].length == 0)
self.user_swaps[_owner].push(address(0x0));
//Add a new swap index for the owner
self.user_swaps_index[_owner][_swap] = self.user_swaps[_owner].length;
//Push a new swap address to the owner's swaps
self.user_swaps[_owner].push(_swap);
//Push a zeroed Balance struct to the swap balances mapping to prevent default value conflicts in swap_balances_index
self.swap_balances[_swap].push(Balance({
owner: 0,
amount: 0
}));
//Add a new owner balance index for the swap
self.swap_balances_index[_swap][_owner] = 1;
//Push the owner's balance to the swap
self.swap_balances[_swap].push(Balance({
owner: _owner,
amount: _supply
}));
emit CreateToken(_owner,_supply);
}
/**
*@dev Called by the factory contract, and pays out to a _party
*@param _party being paid
*@param _swap address
*/
function pay(TokenStorage storage self,address _party, address _swap) public{
require(msg.sender == self.factory_contract);
uint party_balance_index = self.swap_balances_index[_swap][_party];
require(party_balance_index > 0);
uint party_swap_balance = self.swap_balances[_swap][party_balance_index].amount;
//reduces the users totals balance by the amount in that swap
self.user_total_balances[_party] = self.user_total_balances[_party].sub(party_swap_balance);
//reduces the total supply by the amount of that users in that swap
self.total_supply = self.total_supply.sub(party_swap_balance);
//sets the partys balance to zero for that specific swaps party balances
self.swap_balances[_swap][party_balance_index].amount = 0;
}
/**
*@dev Returns the users total balance (sum of tokens in all swaps the user has tokens in)
*@param _owner user address
*@return user total balance
*/
function balanceOf(TokenStorage storage self,address _owner) public constant returns (uint balance) {
return self.user_total_balances[_owner];
}
/**
*@dev Getter for the total_supply of tokens in the contract
*@return total supply
*/
function totalSupply(TokenStorage storage self) public constant returns (uint _total_supply) {
return self.total_supply;
}
/**
*@dev Removes the address from the swap balances for a swap, and moves the last address in the
*swap into their place
*@param _remove address of prevous owner
*@param _swap address used to get last addrss of the swap to replace the removed address
*/
function removeFromSwapBalances(TokenStorage storage self,address _remove, address _swap) internal {
uint last_address_index = self.swap_balances[_swap].length.sub(1);
address last_address = self.swap_balances[_swap][last_address_index].owner;
//If the address we want to remove is the final address in the swap
if (last_address != _remove) {
uint remove_index = self.swap_balances_index[_swap][_remove];
//Update the swap's balance index of the last address to that of the removed address index
self.swap_balances_index[_swap][last_address] = remove_index;
//Set the swap's Balance struct at the removed index to the Balance struct of the last address
self.swap_balances[_swap][remove_index] = self.swap_balances[_swap][last_address_index];
}
//Remove the swap_balances index for this address
delete self.swap_balances_index[_swap][_remove];
//Finally, decrement the swap balances length
self.swap_balances[_swap].length = self.swap_balances[_swap].length.sub(1);
}
/**
*@dev This is the main function to update the mappings when a transfer happens
*@param _from address to send funds from
*@param _to address to send funds to
*@param _amount amount of token to send
*/
function transferHelper(TokenStorage storage self,address _from, address _to, uint _amount) internal {
//Get memory copies of the swap arrays for the sender and reciever
address[] memory from_swaps = self.user_swaps[_from];
//Iterate over sender's swaps in reverse order until enough tokens have been transferred
for (uint i = from_swaps.length.sub(1); i > 0; i--) {
//Get the index of the sender's balance for the current swap
uint from_swap_user_index = self.swap_balances_index[from_swaps[i]][_from];
Balance memory from_user_bal = self.swap_balances[from_swaps[i]][from_swap_user_index];
//If the current swap will be entirely depleted - we remove all references to it for the sender
if (_amount >= from_user_bal.amount) {
_amount -= from_user_bal.amount;
//If this swap is to be removed, we know it is the (current) last swap in the user's user_swaps list, so we can simply decrement the length to remove it
self.user_swaps[_from].length = self.user_swaps[_from].length.sub(1);
//Remove the user swap index for this swap
delete self.user_swaps_index[_from][from_swaps[i]];
//If the _to address already holds tokens from this swap
if (self.user_swaps_index[_to][from_swaps[i]] != 0) {
//Get the index of the _to balance in this swap
uint to_balance_index = self.swap_balances_index[from_swaps[i]][_to];
assert(to_balance_index != 0);
//Add the _from tokens to _to
self.swap_balances[from_swaps[i]][to_balance_index].amount = self.swap_balances[from_swaps[i]][to_balance_index].amount.add(from_user_bal.amount);
//Remove the _from address from this swap's balance array
removeFromSwapBalances(self,_from, from_swaps[i]);
} else {
//Prepare to add a new swap by assigning the swap an index for _to
if (self.user_swaps[_to].length == 0){
self.user_swaps[_to].push(address(0x0));
}
self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length;
//Add the new swap to _to
self.user_swaps[_to].push(from_swaps[i]);
//Give the reciever the sender's balance for this swap
self.swap_balances[from_swaps[i]][from_swap_user_index].owner = _to;
//Give the reciever the sender's swap balance index for this swap
self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances_index[from_swaps[i]][_from];
//Remove the swap balance index from the sending party
delete self.swap_balances_index[from_swaps[i]][_from];
}
//If there is no more remaining to be removed, we break out of the loop
if (_amount == 0)
break;
} else {
//The amount in this swap is more than the amount we still need to transfer
uint to_swap_balance_index = self.swap_balances_index[from_swaps[i]][_to];
//If the _to address already holds tokens from this swap
if (self.user_swaps_index[_to][from_swaps[i]] != 0) {
//Because both addresses are in this swap, and neither will be removed, we simply update both swap balances
self.swap_balances[from_swaps[i]][to_swap_balance_index].amount = self.swap_balances[from_swaps[i]][to_swap_balance_index].amount.add(_amount);
} else {
//Prepare to add a new swap by assigning the swap an index for _to
if (self.user_swaps[_to].length == 0){
self.user_swaps[_to].push(address(0x0));
}
self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length;
//And push the new swap
self.user_swaps[_to].push(from_swaps[i]);
//_to is not in this swap, so we give this swap a new balance index for _to
self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances[from_swaps[i]].length;
//And push a new balance for _to
self.swap_balances[from_swaps[i]].push(Balance({
owner: _to,
amount: _amount
}));
}
//Finally, update the _from user's swap balance
self.swap_balances[from_swaps[i]][from_swap_user_index].amount = self.swap_balances[from_swaps[i]][from_swap_user_index].amount.sub(_amount);
//Because we have transferred the last of the amount to the reciever, we break;
break;
}
}
}
/**
*@dev ERC20 compliant transfer function
*@param _to Address to send funds to
*@param _amount Amount of token to send
*@return true for successful
*/
function transfer(TokenStorage storage self, address _to, uint _amount) public returns (bool) {
require(isWhitelisted(self,_to));
uint balance_owner = self.user_total_balances[msg.sender];
if (
_to == msg.sender ||
_to == address(0) ||
_amount == 0 ||
balance_owner < _amount
) return false;
transferHelper(self,msg.sender, _to, _amount);
self.user_total_balances[msg.sender] = self.user_total_balances[msg.sender].sub(_amount);
self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
*@dev ERC20 compliant transferFrom function
*@param _from address to send funds from (must be allowed, see approve function)
*@param _to address to send funds to
*@param _amount amount of token to send
*@return true for successful
*/
function transferFrom(TokenStorage storage self, address _from, address _to, uint _amount) public returns (bool) {
require(isWhitelisted(self,_to));
uint balance_owner = self.user_total_balances[_from];
uint sender_allowed = self.allowed[_from][msg.sender];
if (
_to == _from ||
_to == address(0) ||
_amount == 0 ||
balance_owner < _amount ||
sender_allowed < _amount
) return false;
transferHelper(self,_from, _to, _amount);
self.user_total_balances[_from] = self.user_total_balances[_from].sub(_amount);
self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);
self.allowed[_from][msg.sender] = self.allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
*@dev ERC20 compliant approve function
*@param _spender party that msg.sender approves for transferring funds
*@param _amount amount of token to approve for sending
*@return true for successful
*/
function approve(TokenStorage storage self, address _spender, uint _amount) public returns (bool) {
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
*@dev Counts addresses involved in the swap based on the length of balances array for _swap
*@param _swap address
*@return the length of the balances array for the swap
*/
function addressCount(TokenStorage storage self, address _swap) public constant returns (uint) {
return self.swap_balances[_swap].length;
}
/**
*@dev Gets the owner address and amount by specifying the swap address and index
*@param _ind specified index in the swap
*@param _swap specified swap address
*@return the owner address associated with a particular index in a particular swap
*@return the amount to transfer associated with a particular index in a particular swap
*/
function getBalanceAndHolderByIndex(TokenStorage storage self, uint _ind, address _swap) public constant returns (uint, address) {
return (self.swap_balances[_swap][_ind].amount, self.swap_balances[_swap][_ind].owner);
}
/**
*@dev Gets the index by specifying the swap and owner addresses
*@param _owner specifed address
*@param _swap specified swap address
*@return the index associated with the _owner address in a particular swap
*/
function getIndexByAddress(TokenStorage storage self, address _owner, address _swap) public constant returns (uint) {
return self.swap_balances_index[_swap][_owner];
}
/**
*@dev Look up how much the spender or contract is allowed to spend?
*@param _owner
*@param _spender party approved for transfering funds
*@return the allowed amount _spender can spend of _owner's balance
*/
function allowance(TokenStorage storage self, address _owner, address _spender) public constant returns (uint) {
return self.allowed[_owner][_spender];
}
}
/**
*The DRCT_Token is an ERC20 compliant token representing the payout of the swap contract
*specified in the Factory contract.
*Each Factory contract is specified one DRCT Token and the token address can contain many
*different swap contracts that are standardized at the Factory level.
*The logic for the functions in this contract is housed in the DRCTLibary.sol.
*/
contract DRCT_Token {
using DRCTLibrary for DRCTLibrary.TokenStorage;
/*Variables*/
DRCTLibrary.TokenStorage public drct;
/*Functions*/
/**
*@dev Constructor - sets values for token name and token supply, as well as the
*factory_contract, the swap.
*@param _factory
*/
constructor() public {
drct.startToken(msg.sender);
}
/**
*@dev Token Creator - This function is called by the factory contract and creates new tokens
*for the user
*@param _supply amount of DRCT tokens created by the factory contract for this swap
*@param _owner address
*@param _swap address
*/
function createToken(uint _supply, address _owner, address _swap) public{
drct.createToken(_supply,_owner,_swap);
}
/**
*@dev gets the factory address
*/
function getFactoryAddress() external view returns(address){
return drct.getFactoryAddress();
}
/**
*@dev Called by the factory contract, and pays out to a _party
*@param _party being paid
*@param _swap address
*/
function pay(address _party, address _swap) public{
drct.pay(_party,_swap);
}
/**
*@dev Returns the users total balance (sum of tokens in all swaps the user has tokens in)
*@param _owner user address
*@return user total balance
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return drct.balanceOf(_owner);
}
/**
*@dev Getter for the total_supply of tokens in the contract
*@return total supply
*/
function totalSupply() public constant returns (uint _total_supply) {
return drct.totalSupply();
}
/**
*ERC20 compliant transfer function
*@param _to Address to send funds to
*@param _amount Amount of token to send
*@return true for successful
*/
function transfer(address _to, uint _amount) public returns (bool) {
return drct.transfer(_to,_amount);
}
/**
*@dev ERC20 compliant transferFrom function
*@param _from address to send funds from (must be allowed, see approve function)
*@param _to address to send funds to
*@param _amount amount of token to send
*@return true for successful transfer
*/
function transferFrom(address _from, address _to, uint _amount) public returns (bool) {
return drct.transferFrom(_from,_to,_amount);
}
/**
*@dev ERC20 compliant approve function
*@param _spender party that msg.sender approves for transferring funds
*@param _amount amount of token to approve for sending
*@return true for successful
*/
function approve(address _spender, uint _amount) public returns (bool) {
return drct.approve(_spender,_amount);
}
/**
*@dev Counts addresses involved in the swap based on the length of balances array for _swap
*@param _swap address
*@return the length of the balances array for the swap
*/
function addressCount(address _swap) public constant returns (uint) {
return drct.addressCount(_swap);
}
/**
*@dev Gets the owner address and amount by specifying the swap address and index
*@param _ind specified index in the swap
*@param _swap specified swap address
*@return the amount to transfer associated with a particular index in a particular swap
*@return the owner address associated with a particular index in a particular swap
*/
function getBalanceAndHolderByIndex(uint _ind, address _swap) public constant returns (uint, address) {
return drct.getBalanceAndHolderByIndex(_ind,_swap);
}
/**
*@dev Gets the index by specifying the swap and owner addresses
*@param _owner specifed address
*@param _swap specified swap address
*@return the index associated with the _owner address in a particular swap
*/
function getIndexByAddress(address _owner, address _swap) public constant returns (uint) {
return drct.getIndexByAddress(_owner,_swap);
}
/**
*@dev Look up how much the spender or contract is allowed to spend?
*@param _owner address
*@param _spender party approved for transfering funds
*@return the allowed amount _spender can spend of _owner's balance
*/
function allowance(address _owner, address _spender) public constant returns (uint) {
return drct.allowance(_owner,_spender);
}
}
//ERC20 function interface with create token and withdraw
interface Wrapped_Ether_Interface {
function totalSupply() external constant returns (uint);
function balanceOf(address _owner) external constant returns (uint);
function transfer(address _to, uint _amount) external returns (bool);
function transferFrom(address _from, address _to, uint _amount) external returns (bool);
function approve(address _spender, uint _amount) external returns (bool);
function allowance(address _owner, address _spender) external constant returns (uint);
function withdraw(uint _value) external;
function createToken() external;
}
interface Membership_Interface {
function getMembershipType(address _member) external constant returns(uint);
}
/**
*The Factory contract sets the standardized variables and also deploys new contracts based on
*these variables for the user.
*/
contract Factory {
using SafeMath for uint256;
/*Variables*/
//Addresses of the Factory owner and oracle. For oracle information,
//check www.github.com/DecentralizedDerivatives/Oracles
address public owner;
address public oracle_address;
//Address of the user contract
address public user_contract;
//Address of the deployer contract
address internal deployer_address;
Deployer_Interface internal deployer;
address public token;
//A fee for creating a swap in wei. Plan is for this to be zero, however can be raised to prevent spam
uint public fee;
//swap fee
uint public swapFee;
//Duration of swap contract in days
uint public duration;
//Multiplier of reference rate. 2x refers to a 50% move generating a 100% move in the contract payout values
uint public multiplier;
//Token_ratio refers to the number of DRCT Tokens a party will get based on the number of base tokens. As an example, 1e15 indicates that a party will get 1000 DRCT Tokens based upon 1 ether of wrapped wei.
uint public token_ratio;
//Array of deployed contracts
address[] public contracts;
uint[] public startDates;
address public memberContract;
mapping(uint => bool) whitelistedTypes;
mapping(address => uint) public created_contracts;
mapping(address => uint) public token_dates;
mapping(uint => address) public long_tokens;
mapping(uint => address) public short_tokens;
mapping(address => uint) public token_type; //1=short 2=long
/*Events*/
//Emitted when a Swap is created
event ContractCreation(address _sender, address _created);
/*Modifiers*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*Functions*/
/**
*@dev Constructor - Sets owner
*/
constructor() public {
owner = msg.sender;
}
/**
*@dev constructor function for cloned factory
*/
function init(address _owner) public{
require(owner == address(0));
owner = _owner;
}
/**
*@dev Sets the Membership contract address
*@param _memberContract The new membership address
*/
function setMemberContract(address _memberContract) public onlyOwner() {
memberContract = _memberContract;
}
/**
*@dev Sets the member types/permissions for those whitelisted
*@param _memberTypes is the list of member types
*/
function setWhitelistedMemberTypes(uint[] _memberTypes) public onlyOwner(){
whitelistedTypes[0] = false;
for(uint i = 0; i<_memberTypes.length;i++){
whitelistedTypes[_memberTypes[i]] = true;
}
}
/**
*@dev Checks the membership type/permissions for whitelisted members
*@param _member address to get membership type from
*/
function isWhitelisted(address _member) public view returns (bool){
Membership_Interface Member = Membership_Interface(memberContract);
return whitelistedTypes[Member.getMembershipType(_member)];
}
/**
*@dev Gets long and short token addresses based on specified date
*@param _date
*@return short and long tokens' addresses
*/
function getTokens(uint _date) public view returns(address, address){
return(long_tokens[_date],short_tokens[_date]);
}
/**
*@dev Gets the type of Token (long and short token) for the specifed
*token address
*@param _token address
*@return token type short = 1 and long = 2
*/
function getTokenType(address _token) public view returns(uint){
return(token_type[_token]);
}
/**
*@dev Updates the fee amount
*@param _fee is the new fee amount
*/
function setFee(uint _fee) public onlyOwner() {
fee = _fee;
}
/**
*@dev Updates the swap fee amount
*@param _swapFee is the new swap fee amount
*/
function setSwapFee(uint _swapFee) public onlyOwner() {
swapFee = _swapFee;
}
/**
*@dev Sets the deployer address
*@param _deployer is the new deployer address
*/
function setDeployer(address _deployer) public onlyOwner() {
deployer_address = _deployer;
deployer = Deployer_Interface(_deployer);
}
/**
*@dev Sets the user_contract address
*@param _userContract is the new userContract address
*/
function setUserContract(address _userContract) public onlyOwner() {
user_contract = _userContract;
}
/**
*@dev Sets token ratio, swap duration, and multiplier variables for a swap.
*@param _token_ratio the ratio of the tokens
*@param _duration the duration of the swap, in days
*@param _multiplier the multiplier used for the swap
*@param _swapFee the swap fee
*/
function setVariables(uint _token_ratio, uint _duration, uint _multiplier, uint _swapFee) public onlyOwner() {
require(_swapFee < 10000);
token_ratio = _token_ratio;
duration = _duration;
multiplier = _multiplier;
swapFee = _swapFee;
}
/**
*@dev Sets the address of the base tokens used for the swap
*@param _token The address of a token to be used as collateral
*/
function setBaseToken(address _token) public onlyOwner() {
token = _token;
}
/**
*@dev Allows a user to deploy a new swap contract, if they pay the fee
*@param _start_date the contract start date
*@return new_contract address for he newly created swap address and calls
*event 'ContractCreation'
*/
function deployContract(uint _start_date) public payable returns (address) {
require(msg.value >= fee && isWhitelisted(msg.sender));
require(_start_date % 86400 == 0);
address new_contract = deployer.newContract(msg.sender, user_contract, _start_date);
contracts.push(new_contract);
created_contracts[new_contract] = _start_date;
emit ContractCreation(msg.sender,new_contract);
return new_contract;
}
/**
*@dev Deploys DRCT tokens for given start date
*@param _start_date of contract
*/
function deployTokenContract(uint _start_date) public{
address _token;
require(_start_date % 86400 == 0);
require(long_tokens[_start_date] == address(0) && short_tokens[_start_date] == address(0));
_token = new DRCT_Token();
token_dates[_token] = _start_date;
long_tokens[_start_date] = _token;
token_type[_token]=2;
_token = new DRCT_Token();
token_type[_token]=1;
short_tokens[_start_date] = _token;
token_dates[_token] = _start_date;
startDates.push(_start_date);
}
/**
*@dev Deploys new tokens on a DRCT_Token contract -- called from within a swap
*@param _supply The number of tokens to create
*@param _party the address to send the tokens to
*@param _start_date the start date of the contract
*@returns ltoken the address of the created DRCT long tokens
*@returns stoken the address of the created DRCT short tokens
*@returns token_ratio The ratio of the created DRCT token
*/
function createToken(uint _supply, address _party, uint _start_date) public returns (address, address, uint) {
require(created_contracts[msg.sender] == _start_date);
address ltoken = long_tokens[_start_date];
address stoken = short_tokens[_start_date];
require(ltoken != address(0) && stoken != address(0));
DRCT_Token drct_interface = DRCT_Token(ltoken);
drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);
drct_interface = DRCT_Token(stoken);
drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);
return (ltoken, stoken, token_ratio);
}
/**
*@dev Allows the owner to set a new oracle address
*@param _new_oracle_address
*/
function setOracleAddress(address _new_oracle_address) public onlyOwner() {
oracle_address = _new_oracle_address;
}
/**
*@dev Allows the owner to set a new owner address
*@param _new_owner the new owner address
*/
function setOwner(address _new_owner) public onlyOwner() {
owner = _new_owner;
}
/**
*@dev Allows the owner to pull contract creation fees
*@return the withdrawal fee _val and the balance where is the return function?
*/
function withdrawFees() public onlyOwner(){
Wrapped_Ether_Interface token_interface = Wrapped_Ether_Interface(token);
uint _val = token_interface.balanceOf(address(this));
if(_val > 0){
token_interface.withdraw(_val);
}
owner.transfer(address(this).balance);
}
/**
*@dev fallback function
*/
function() public payable {
}
/**
*@dev Returns a tuple of many private variables.
*The variables from this function are pass through to the TokenLibrary.getVariables function
*@returns oracle_adress is the address of the oracle
*@returns duration is the duration of the swap
*@returns multiplier is the multiplier for the swap
*@returns token is the address of token
*@returns _swapFee is the swap fee
*/
function getVariables() public view returns (address, uint, uint, address,uint){
return (oracle_address,duration, multiplier, token,swapFee);
}
/**
*@dev Pays out to a DRCT token
*@param _party is the address being paid
*@param _token_add token to pay out
*/
function payToken(address _party, address _token_add) public {
require(created_contracts[msg.sender] > 0);
DRCT_Token drct_interface = DRCT_Token(_token_add);
drct_interface.pay(_party, msg.sender);
}
/**
*@dev Counts number of contacts created by this factory
*@return the number of contracts
*/
function getCount() public constant returns(uint) {
return contracts.length;
}
/**
*@dev Counts number of start dates in this factory
*@return the number of active start dates
*/
function getDateCount() public constant returns(uint) {
return startDates.length;
}
}
/**
*This contracts helps clone factories and swaps through the Deployer.sol and MasterDeployer.sol.
*The address of the targeted contract to clone has to be provided.
*/
contract CloneFactory {
/*Variables*/
address internal owner;
/*Events*/
event CloneCreated(address indexed target, address clone);
/*Modifiers*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*Functions*/
constructor() public{
owner = msg.sender;
}
/**
*@dev Allows the owner to set a new owner address
*@param _owner the new owner address
*/
function setOwner(address _owner) public onlyOwner(){
owner = _owner;
}
/**
*@dev Creates factory clone
*@param _target is the address being cloned
*@return address for clone
*/
function createClone(address target) internal returns (address result) {
bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd";
bytes20 targetBytes = bytes20(target);
for (uint i = 0; i < 20; i++) {
clone[26 + i] = targetBytes[i];
}
assembly {
let len := mload(clone)
let data := add(clone, 0x20)
result := create(0, data, len)
}
}
}
/**
*This contract deploys a factory contract and uses CloneFactory to clone the factory
*specified.
*/
contract MasterDeployer is CloneFactory{
using SafeMath for uint256;
/*Variables*/
address[] factory_contracts;
address private factory;
mapping(address => uint) public factory_index;
/*Events*/
event NewFactory(address _factory);
/*Functions*/
/**
*@dev Initiates the factory_contract array with address(0)
*/
constructor() public {
factory_contracts.push(address(0));
}
/**
*@dev Set factory address to clone
*@param _factory address to clone
*/
function setFactory(address _factory) public onlyOwner(){
factory = _factory;
}
/**
*@dev creates a new factory by cloning the factory specified in setFactory.
*@return _new_fac which is the new factory address
*/
function deployFactory() public onlyOwner() returns(address){
address _new_fac = createClone(factory);
factory_index[_new_fac] = factory_contracts.length;
factory_contracts.push(_new_fac);
Factory(_new_fac).init(msg.sender);
emit NewFactory(_new_fac);
return _new_fac;
}
/**
*@dev Removes the factory specified
*@param _factory address to remove
*/
function removeFactory(address _factory) public onlyOwner(){
require(_factory != address(0) && factory_index[_factory] != 0);
uint256 fIndex = factory_index[_factory];
uint256 lastFactoryIndex = factory_contracts.length.sub(1);
address lastFactory = factory_contracts[lastFactoryIndex];
factory_contracts[fIndex] = lastFactory;
factory_index[lastFactory] = fIndex;
factory_contracts.length--;
factory_index[_factory] = 0;
}
/**
*@dev Counts the number of factories
*@returns the number of active factories
*/
function getFactoryCount() public constant returns(uint){
return factory_contracts.length - 1;
}
/**
*@dev Returns the factory address for the specified index
*@param _index for factory to look up in the factory_contracts array
*@return factory address for the index specified
*/
function getFactorybyIndex(uint _index) public constant returns(address){
return factory_contracts[_index];
}
}
|
ERC20 compliant transfer function _to Address to send funds to _amount Amount of token to sendreturn true for successful/
|
function transfer(address _to, uint _amount) public returns (bool) {
return drct.transfer(_to,_amount);
}
| 2,080,647
|
./partial_match/1/0x21997AEc292b838a87822219b5886349691C3fab/sources/TokenNMintERC20Token.sol
|
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");
uint256 c = a - b;
return c;
}
| 10,996,603
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.4;
import "@prb/contracts/access/Ownable.sol";
import "@prb/contracts/token/erc20/Erc20.sol";
import "@prb/contracts/token/erc20/Erc20Permit.sol";
import "@prb/contracts/token/erc20/Erc20Recover.sol";
import "@prb/contracts/token/erc20/SafeErc20.sol";
import "./IHToken.sol";
import "../balance-sheet/IBalanceSheetV2.sol";
import "../fintroller/IFintroller.sol";
/// @title HToken
/// @author Hifi
contract HToken is
Ownable, // one dependency
Erc20, // one dependency
Erc20Permit, // four dependencies
IHToken, // five dependencies
Erc20Recover // five dependencies
{
using SafeErc20 for IErc20;
/// PUBLIC STORAGE ///
/// @inheritdoc IHToken
IBalanceSheetV2 public override balanceSheet;
/// @inheritdoc IHToken
IFintroller public override fintroller;
/// @inheritdoc IHToken
uint256 public override maturity;
/// @inheritdoc IHToken
uint256 public override totalUnderlyingReserve;
/// @inheritdoc IHToken
IErc20 public override underlying;
/// @inheritdoc IHToken
uint256 public override underlyingPrecisionScalar;
/// INTERNAL STORAGE ///
/// @dev Underlying depositor balances.
mapping(address => uint256) internal depositorBalances;
/// CONSTRUCTOR ///
/// @notice The hToken always has 18 decimals.
/// @param name_ Erc20 name of this token.
/// @param symbol_ Erc20 symbol of this token.
/// @param maturity_ Unix timestamp in seconds for when this token matures.
/// @param balanceSheet_ The address of the BalanceSheet contract to connect to.
/// @param fintroller_ The address of the Fintroller contract to connect to.
/// @param underlying_ The contract address of the underlying asset.
constructor(
string memory name_,
string memory symbol_,
uint256 maturity_,
IBalanceSheetV2 balanceSheet_,
IFintroller fintroller_,
IErc20 underlying_
) Erc20Permit(name_, symbol_, 18) Ownable() {
// Set the maturity.
if (maturity_ <= block.timestamp) {
revert HToken__MaturityPassed(block.timestamp, maturity_);
}
maturity = maturity_;
// Set the BalanceSheet contract.
balanceSheet = balanceSheet_;
// Set the Fintroller contract.
fintroller = fintroller_;
// Set the underlying contract and calculate the precision scalar.
uint256 underlyingDecimals = underlying_.decimals();
if (underlyingDecimals == 0) {
revert HToken__UnderlyingDecimalsZero();
}
if (underlyingDecimals > 18) {
revert HToken__UnderlyingDecimalsOverflow(underlyingDecimals);
}
underlyingPrecisionScalar = 10**(18 - underlyingDecimals);
underlying = underlying_;
// Set the list of non-recoverable tokens.
nonRecoverableTokens.push(underlying);
isRecoverInitialized = true;
}
/// PUBLIC CONSTANT FUNCTIONS ///
function getDepositorBalance(address depositor) external view override returns (uint256 amount) {
return depositorBalances[depositor];
}
/// @inheritdoc IHToken
function isMatured() public view override returns (bool) {
return block.timestamp >= maturity;
}
/// PUBLIC NON-CONSTANT FUNCTIONS ///
/// @inheritdoc IHToken
function burn(address holder, uint256 burnAmount) external override {
// Checks: the caller is the BalanceSheet.
if (msg.sender != address(balanceSheet)) {
revert HToken__BurnNotAuthorized(msg.sender);
}
// Effects: burns the hTokens.
burnInternal(holder, burnAmount);
// Emit a Burn and a Transfer event.
emit Burn(holder, burnAmount);
}
/// @inheritdoc IHToken
function depositUnderlying(uint256 underlyingAmount) external override {
// Checks: the Fintroller allows this action to be performed.
if (!fintroller.getDepositUnderlyingAllowed(this)) {
revert HToken__DepositUnderlyingNotAllowed();
}
// Checks: the zero edge case.
if (underlyingAmount == 0) {
revert HToken__DepositUnderlyingZero();
}
// Effects: update storage.
totalUnderlyingReserve += underlyingAmount;
// Effects: update the balance of the depositor.
depositorBalances[msg.sender] += underlyingAmount;
// Normalize the underlying amount to 18 decimals.
uint256 hTokenAmount = normalize(underlyingAmount);
// Effects: mint the hTokens.
mintInternal(msg.sender, hTokenAmount);
// Interactions: perform the Erc20 transfer.
underlying.safeTransferFrom(msg.sender, address(this), underlyingAmount);
emit DepositUnderlying(msg.sender, underlyingAmount, hTokenAmount);
}
/// @inheritdoc IHToken
function mint(address beneficiary, uint256 mintAmount) external override {
// Checks: the caller is the BalanceSheet.
if (msg.sender != address(balanceSheet)) {
revert HToken__MintNotAuthorized(msg.sender);
}
// Effects: print the new hTokens into existence.
mintInternal(beneficiary, mintAmount);
// Emit a Mint event.
emit Mint(beneficiary, mintAmount);
}
/// @inheritdoc IHToken
function redeem(uint256 underlyingAmount) external override {
// Checks: before maturation.
if (!isMatured()) {
revert HToken__BondNotMatured(block.timestamp, maturity);
}
// Checks: the zero edge case.
if (underlyingAmount == 0) {
revert HToken__RedeemZero();
}
// Checks: there is enough liquidity.
if (underlyingAmount > totalUnderlyingReserve) {
revert HToken__RedeemInsufficientLiquidity(underlyingAmount, totalUnderlyingReserve);
}
// Effects: decrease the reserves of underlying.
totalUnderlyingReserve -= underlyingAmount;
// Normalize the underlying amount to 18 decimals.
uint256 hTokenAmount = normalize(underlyingAmount);
// Effects: burn the hTokens.
burnInternal(msg.sender, hTokenAmount);
// Interactions: perform the Erc20 transfer.
underlying.safeTransfer(msg.sender, underlyingAmount);
emit Redeem(msg.sender, underlyingAmount, hTokenAmount);
}
/// @inheritdoc IHToken
function withdrawUnderlying(uint256 underlyingAmount) external override {
// Checks: after maturation, depositors should call the `redeem` function instead.
if (isMatured()) {
revert HToken__BondMatured(block.timestamp, maturity);
}
// Checks: the zero edge case.
if (underlyingAmount == 0) {
revert HToken__WithdrawUnderlyingZero();
}
// Checks: the depositor has enough underlying.
uint256 availableAmount = depositorBalances[msg.sender];
if (availableAmount < underlyingAmount) {
revert HToken__WithdrawUnderlyingUnderflow(msg.sender, availableAmount, underlyingAmount);
}
// Effects: update storage.
totalUnderlyingReserve -= underlyingAmount;
// Effects: update the balance of the depositor.
depositorBalances[msg.sender] -= underlyingAmount;
// Normalize the underlying amount to 18 decimals.
uint256 hTokenAmount = normalize(underlyingAmount);
// Effects: burn the hTokens.
burnInternal(msg.sender, hTokenAmount);
// Interactions: perform the Erc20 transfer.
underlying.safeTransfer(msg.sender, underlyingAmount);
emit WithdrawUnderlying(msg.sender, underlyingAmount, hTokenAmount);
}
/// @inheritdoc IHToken
function _setBalanceSheet(IBalanceSheetV2 newBalanceSheet) external override onlyOwner {
// Effects: update storage.
IBalanceSheetV2 oldBalanceSheet = balanceSheet;
balanceSheet = newBalanceSheet;
emit SetBalanceSheet(owner, oldBalanceSheet, newBalanceSheet);
}
/// INTERNAL CONSTANT FUNCTIONS ///
/// @notice Upscales the underlying amount to normalized form, i.e. 18 decimals of precision.
/// @param underlyingAmount The underlying amount with its actual decimals of precision.
/// @param normalizedUnderlyingAmount The underlying amount with 18 decimals of precision.
function normalize(uint256 underlyingAmount) internal view returns (uint256 normalizedUnderlyingAmount) {
normalizedUnderlyingAmount = underlyingPrecisionScalar != 1
? underlyingAmount * underlyingPrecisionScalar
: underlyingAmount;
}
}
|
@inheritdoc IHToken Effects: update storage.
|
function _setBalanceSheet(IBalanceSheetV2 newBalanceSheet) external override onlyOwner {
IBalanceSheetV2 oldBalanceSheet = balanceSheet;
balanceSheet = newBalanceSheet;
emit SetBalanceSheet(owner, oldBalanceSheet, newBalanceSheet);
}
| 6,419,845
|
./full_match/5/0xd33aD018417d19a9d1e1575AEa1cc40cD04ACC3F/sources/contracts/RaiseFundContract.sol
|
function for owner to withdraw funds
|
function withdraw(address payable _owner) public {
require(msg.sender == _owner, "Only owner can withdraw the funds.");
uint256 campaignIndex;
for (uint256 i = 0; i < numberOfCampaigns; i++) {
if (campaigns[i].owner == _owner) {
campaignIndex = i;
break;
}
}
require(campaignIndex < numberOfCampaigns, "Invalid campaign ID");
require(
campaigns[campaignIndex].amountRaised > 0,
"No funds to withdraw"
);
_owner.transfer(campaigns[campaignIndex].amountRaised);
emit FundWithdrawn(
campaignIndex,
campaigns[campaignIndex].name,
campaigns[campaignIndex].amountRaised
);
campaigns[campaignIndex].amountRaised = 0;
}
| 1,875,781
|
pragma solidity ^0.4.17;
import "./ByzantineTileBase.sol";
import "./ERC721.sol";
import "./ERC721Metadata.sol";
import "./SafeMath.sol";
/// @title The facet of the ByzantineTile core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Byzantine (https://byzantine.network)
/// @author for CryptoKitties Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the ByzantineTileCore contract documentation to understand how the various contract facets are arranged.
contract ByzantineTileOwnership is ByzantineTileBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "Byzantine Space Quest";
string public constant symbol = "BYZSQ";
// The contract that will return tile metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
using SafeMath for uint256;
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular tile.
/// @param _claimant the address we are validating against.
/// @param _tokenId tile id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return byzantineTileIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular tile.
/// @param _claimant the address we are confirming tile is approved for.
/// @param _tokenId tile id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return byzantineTileIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting tiles on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
byzantineTileIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of tiles owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a tile to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// ByzantineTile specifically) or your tile may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the tile to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPausedPresale
{
// freeze tile transfers until the auction date is reached
require(byzantineTileAuctionDate !=0);
// an auction date has been set, only unlock if we are beyond that date
require (now > byzantineTileAuctionDate);
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any tiles.
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of tiles
// through the allow + transferFrom flow.
//require(_to != address(saleAuction));
// You can only send your own tile.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific tile via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the tile that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPausedPresale
{
// freeze tile transfers until the auction date is reached
require(byzantineTileAuctionDate !=0);
// an auction date has been set, only unlock if we are beyond that date
require (now > byzantineTileAuctionDate);
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a tile owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the tile to be transfered.
/// @param _to The address that should take ownership of the tile. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the tile to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any tiles.
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of tiles currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint total) {
total = byzantineTiles.length;
// if there are not tiles in the array yet, the length will return a very large number
if (total != uint256(uint32(total))) {
// then return zero, array is empty
total = 0;
}
}
/// @notice Returns the address currently assigned ownership of a given tile.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = byzantineTileIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all tile IDs assigned to an address.
/// @param _owner The owner whose tiles we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire tile array looking for tiles belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTiles = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all tiles have IDs starting at 1 and increasing
// sequentially up to the totalTiles count.
uint256 tileId;
for (tileId = 1; tileId <= totalTiles; tileId++) {
if (byzantineTileIndexToOwner[tileId] == _owner) {
result[resultIndex] = tileId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the tile whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
|
Transfer a tile owned by another address, for which the calling address has previously been granted transfer approval by the owner. _from The address that owns the tile to be transfered. _to The address that should take ownership of the tile. Can be any address, including the caller. _tokenId The ID of the tile to be transferred. Required for ERC-721 compliance. Safety check to prevent against an unexpected 0x0 default. Disallow transfers to this contract to prevent accidental misuse. The contract should never own any tiles. Check for approval and valid ownership Reassign ownership (also clears pending approvals and emits Transfer event).
|
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
| 13,074,136
|
pragma solidity 0.4.23;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* @notice Checks if the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
// a variable to load `extcodesize` to
uint256 size = 0;
// 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.
// solium-disable-next-line security/no-inline-assembly
assembly {
// retrieve the size of the code at address `addr`
size := extcodesize(addr)
}
// positive size indicates a smart contract address
return size > 0;
}
}
/**
* Library for working with strings, primarily converting
* between strings and integer types
*/
library StringUtils {
/**
* @dev Converts a string to unsigned integer using the specified `base`
* @dev Throws on invalid input
* (wrong characters for a given `base`)
* @dev Throws if given `base` is not supported
* @param a string to convert
* @param base number base, one of 2, 8, 10, 16
* @return a number representing given string
*/
function atoi(string a, uint8 base) internal pure returns (uint256 i) {
// check if the base is valid
require(base == 2 || base == 8 || base == 10 || base == 16);
// convert string into bytes for convenient iteration
bytes memory buf = bytes(a);
// iterate over the string (bytes buffer)
for(uint256 p = 0; p < buf.length; p++) {
// extract the digit
uint8 digit = uint8(buf[p]) - 0x30;
// if digit is greater then 10 – mind the gap
// see `itoa` function for more details
if(digit > 10) {
// remove the gap
digit -= 7;
}
// check if digit meets the base
require(digit < base);
// move to the next digit slot
i *= base;
// add digit to the result
i += digit;
}
// return the result
return i;
}
/**
* @dev Converts a integer to a string using the specified `base`
* @dev Throws if given `base` is not supported
* @param i integer to convert
* @param base number base, one of 2, 8, 10, 16
* @return a string representing given integer
*/
function itoa(uint256 i, uint8 base) internal pure returns (string a) {
// check if the base is valid
require(base == 2 || base == 8 || base == 10 || base == 16);
// for zero input the result is "0" string for any base
if (i == 0) {
return "0";
}
// bytes buffer to put ASCII characters into
bytes memory buf = new bytes(256);
// position within a buffer to be used in cycle
uint256 p = 0;
// extract digits one by one in a cycle
while (i > 0) {
// extract current digit
uint8 digit = uint8(i % base);
// convert it to an ASCII code
// 0x20 is " "
// 0x30-0x39 is "0"-"9"
// 0x41-0x5A is "A"-"Z"
// 0x61-0x7A is "a"-"z" ("A"-"Z" XOR " ")
uint8 ascii = digit + 0x30;
// if digit is greater then 10,
// fix the 0x3A-0x40 gap of punctuation marks
// (7 characters in ASCII table)
if(digit > 10) {
// jump through the gap
ascii += 7;
}
// write character into the buffer
buf[p++] = byte(ascii);
// move to the next digit
i /= base;
}
// `p` contains real length of the buffer now, save it
uint256 length = p;
// reverse the buffer
for(p = 0; p < length / 2; p++) {
// swap elements at position `p` from the beginning and end using XOR:
// https://en.wikipedia.org/wiki/XOR_swap_algorithm
buf[p] ^= buf[length - 1 - p];
buf[length - 1 - p] ^= buf[p];
buf[p] ^= buf[length - 1 - p];
}
// construct string and return
return string(buf);
}
/**
* @dev Concatenates two strings `s1` and `s2`, for example, if
* `s1` == `foo` and `s2` == `bar`, the result `s` == `foobar`
* @param s1 first string
* @param s2 second string
* @return concatenation result s1 + s2
*/
function concat(string s1, string s2) internal pure returns (string s) {
// convert s1 into buffer 1
bytes memory buf1 = bytes(s1);
// convert s2 into buffer 2
bytes memory buf2 = bytes(s2);
// create a buffer for concatenation result
bytes memory buf = new bytes(buf1.length + buf2.length);
// copy buffer 1 into buffer
for(uint256 i = 0; i < buf1.length; i++) {
buf[i] = buf1[i];
}
// copy buffer 2 into buffer
for(uint256 j = buf1.length; j < buf2.length; j++) {
buf[j] = buf2[j - buf1.length];
}
// construct string and return
return string(buf);
}
}
/**
* @dev Access control module provides an API to check
* if specific operation is permitted globally and
* if particular user's has a permission to execute it
*/
contract AccessControl {
/// @notice Role manager is responsible for assigning the roles
/// @dev Role ROLE_ROLE_MANAGER allows executing addOperator/removeOperator
uint256 private constant ROLE_ROLE_MANAGER = 0x10000000;
/// @notice Feature manager is responsible for enabling/disabling
/// global features of the smart contract
/// @dev Role ROLE_FEATURE_MANAGER allows enabling/disabling global features
uint256 private constant ROLE_FEATURE_MANAGER = 0x20000000;
/// @dev Bitmask representing all the possible permissions (super admin role)
uint256 private constant FULL_PRIVILEGES_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/// @dev A bitmask of globally enabled features
uint256 public features;
/// @notice Privileged addresses with defined roles/permissions
/// @notice In the context of ERC20/ERC721 tokens these can be permissions to
/// allow minting tokens, transferring on behalf and so on
/// @dev Maps an address to the permissions bitmask (role), where each bit
/// represents a permission
/// @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
/// represents all possible permissions
mapping(address => uint256) public userRoles;
/// @dev Fired in updateFeatures()
event FeaturesUpdated(address indexed _by, uint256 _requested, uint256 _actual);
/// @dev Fired in addOperator(), removeOperator(), addRole(), removeRole()
event RoleUpdated(address indexed _by, address indexed _to, uint256 _role);
/**
* @dev Creates an access controlled instance
*/
constructor() public {
// contract creator has full privileges
userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
}
/**
* @dev Updates set of the globally enabled features (`f`),
* taking into account sender's permissions.
* @dev Requires sender to have `ROLE_FEATURE_MANAGER` permission.
* @param mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 mask) public {
// call sender nicely - caller
address caller = msg.sender;
// read caller's permissions
uint256 p = userRoles[caller];
// caller should have a permission to update global features
require(__hasRole(p, ROLE_FEATURE_MANAGER));
// taking into account caller's permissions,
// 1) enable features requested
features |= p & mask;
// 2) disable features requested
features &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ mask));
// fire an event
emit FeaturesUpdated(caller, mask, features);
}
/**
* @dev Adds a new `operator` - an address which has
* some extended privileges over the smart contract,
* for example token minting, transferring on behalf, etc.
* @dev Newly added `operator` cannot have any permissions which
* transaction sender doesn't have.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @dev Cannot update existing operator. Throws if `operator` already exists.
* @param operator address of the operator to add
* @param role bitmask representing a set of permissions which
* newly created operator will have
*/
function addOperator(address operator, uint256 role) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// read manager's permissions (role)
uint256 permissions = userRoles[manager];
// check that `operator` doesn't exist
require(userRoles[operator] == 0);
// manager must have a ROLE_ROLE_MANAGER role
require(__hasRole(permissions, ROLE_ROLE_MANAGER));
// recalculate permissions (role) to set:
// we cannot create an operator more powerful then calling `manager`
uint256 r = role & permissions;
// check if we still have some permissions (role) to set
require(r != 0);
// create an operator by persisting his permissions (roles) to storage
userRoles[operator] = r;
// fire an event
emit RoleUpdated(manager, operator, userRoles[operator]);
}
/**
* @dev Deletes an existing `operator`.
* @dev Requires sender to have `ROLE_ROLE_MANAGER` permission.
* @param operator address of the operator to delete
*/
function removeOperator(address operator) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// check if an `operator` exists
require(userRoles[operator] != 0);
// do not allow transaction sender to remove himself
// protects from an accidental removal of all the operators
require(operator != manager);
// manager must have a ROLE_ROLE_MANAGER role
// and he must have all the permissions operator has
require(__hasRole(userRoles[manager], ROLE_ROLE_MANAGER | userRoles[operator]));
// perform operator deletion
delete userRoles[operator];
// fire an event
emit RoleUpdated(manager, operator, 0);
}
/**
* @dev Updates an existing `operator`, adding a specified role to it.
* @dev Note that `operator` cannot receive permission which
* transaction sender doesn't have.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @dev Cannot create a new operator. Throws if `operator` doesn't exist.
* @dev Existing permissions of the `operator` are preserved
* @param operator address of the operator to update
* @param role bitmask representing a set of permissions which
* `operator` will have
*/
function addRole(address operator, uint256 role) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// read manager's permissions (role)
uint256 permissions = userRoles[manager];
// check that `operator` exists
require(userRoles[operator] != 0);
// manager must have a ROLE_ROLE_MANAGER role
require(__hasRole(permissions, ROLE_ROLE_MANAGER));
// recalculate permissions (role) to add:
// we cannot make an operator more powerful then calling `manager`
uint256 r = role & permissions;
// check if we still have some permissions (role) to add
require(r != 0);
// update operator's permissions (roles) in the storage
userRoles[operator] |= r;
// fire an event
emit RoleUpdated(manager, operator, userRoles[operator]);
}
/**
* @dev Updates an existing `operator`, removing a specified role from it.
* @dev Note that permissions which transaction sender doesn't have
* cannot be removed.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @dev Cannot remove all permissions. Throws on such an attempt.
* @param operator address of the operator to update
* @param role bitmask representing a set of permissions which
* will be removed from the `operator`
*/
function removeRole(address operator, uint256 role) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// read manager's permissions (role)
uint256 permissions = userRoles[manager];
// check that we're not removing all the `operator`s permissions
// this is not really required and just causes inconveniences is function use
//require(userRoles[operator] ^ role != 0);
// manager must have a ROLE_ROLE_MANAGER role
require(__hasRole(permissions, ROLE_ROLE_MANAGER));
// recalculate permissions (role) to remove:
// we cannot revoke permissions which calling `manager` doesn't have
uint256 r = role & permissions;
// check if we still have some permissions (role) to revoke
require(r != 0);
// update operator's permissions (roles) in the storage
userRoles[operator] &= FULL_PRIVILEGES_MASK ^ r;
// fire an event
emit RoleUpdated(manager, operator, userRoles[operator]);
}
/// @dev Checks if requested feature is enabled globally on the contract
function __isFeatureEnabled(uint256 featureRequired) internal constant returns(bool) {
// delegate call to `__hasRole`
return __hasRole(features, featureRequired);
}
/// @dev Checks if transaction sender `msg.sender` has all the required permissions `roleRequired`
function __isSenderInRole(uint256 roleRequired) internal constant returns(bool) {
// read sender's permissions (role)
uint256 userRole = userRoles[msg.sender];
// delegate call to `__hasRole`
return __hasRole(userRole, roleRequired);
}
/// @dev Checks if user role `userRole` contain all the permissions required `roleRequired`
function __hasRole(uint256 userRole, uint256 roleRequired) internal pure returns(bool) {
// check the bitmask for the role required and return the result
return userRole & roleRequired == roleRequired;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safe transfers
* from ERC721 asset contracts.
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
interface ERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient after a `transfer`.
* This function MAY throw to revert and reject the transfer.
* Return of other than the magic value MUST result in the transaction being reverted.
* @notice The contract address is always the message sender.
* A wallet/broker/auction application MUST implement the wallet interface
* if it will accept safe transfers.
* @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(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
contract ERC165 {
/**
* 0x01ffc9a7 == bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
// register itself in a lookup table
_registerInterface(InterfaceId_ERC165);
}
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165.
* This function uses less than 30,000 gas.
* @param _interfaceId The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `interfaceID` and
* `interfaceID` is not 0xffffffff, `false` otherwise
*/
function supportsInterface(bytes4 _interfaceId) public constant returns (bool) {
// find if interface is supported using a lookup table
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
/**
* @notice Library for working with fractions.
* @notice A fraction is represented by two numbers - nominator and denominator.
* @dev A fraction is represented as uint16,
* higher 8 bits representing nominator
* and lower 8 bits representing denominator
*/
library Fractions16 {
/**
* @dev Creates proper fraction with nominator < denominator
* @dev Throws if nominator is equal or greater then denominator
* @dev Throws if denominator is zero
* @param n fraction nominator
* @param d fraction denominator
* @return fraction with nominator and denominator specified
*/
function createProperFraction16(uint8 n, uint8 d) internal pure returns (uint16) {
// denominator cannot be zero by the definition of division
require(d != 0);
// fraction has to be proper
require(n < d);
// construct fraction and return
return uint16(n) << 8 | d;
}
/**
* @dev Converts a proper fraction to its percent representation,
* rounding down the value. For example,
* toPercent(1/10) is 10,
* toPercent(37/100) is 37,
* toPercent(37/1000) is 3
* toPercent(19/37) is 51
* @dev Supports proper fractions and 'one' (nominator equal to denominator),
* which is equal to 100%
* @dev Throws if nominator is bigger than denominator
* @param f positive proper fraction
* @return a value in a range [0..100]
*/
function toPercent(uint16 f) internal pure returns(uint8) {
// extract nominator and denominator
uint8 nominator = getNominator(f);
uint8 denominator = getDenominator(f);
// for a fraction representing one just return 100%
if(nominator == denominator) {
// one is 100%
return 100;
}
// next section of code is for proper fractions only
require(nominator < denominator);
// since fraction is proper one it safe to perform straight forward calculation
// the only thing to worry - possible arithmetic overflow
return uint8(100 * uint16(nominator) / denominator);
}
/**
* @dev Checks if a fraction represents zero (nominator is zero)
* @param f a fraction
* @return true if fraction is zero (nominator is zero), false otherwise
*/
function isZero(uint16 f) internal pure returns(bool) {
// just check if the nominator is zero
return getNominator(f) == 0;
}
/**
* @dev Checks if a fraction represents one (nominator is equal to denominator)
* @param f a fraction
* @return true if fraction is one (nominator is equal to denominator), false otherwise
*/
function isOne(uint16 f) internal pure returns(bool) {
// just check if the nominator is equal to denominator
return getNominator(f) == getDenominator(f);
}
/**
* @dev Checks if a fraction is proper (nominator is less than denominator)
* @param f a fraction
* @return true if fraction is proper (nominator is less than denominator), false otherwise
*/
function isProper(uint16 f) internal pure returns(bool) {
// just check that nominator is less than denominator
// this automatically ensures denominator is not zero
return getNominator(f) < getDenominator(f);
}
/**
* @dev Extracts fraction nominator
* @param f a fraction
* @return nominator
*/
function getNominator(uint16 f) internal pure returns(uint8) {
return uint8(f >> 8);
}
/**
* @dev Extracts fraction denominator
* @param f a fraction
* @return denominator
*/
function getDenominator(uint16 f) internal pure returns(uint8) {
return uint8(f);
}
/**
* @dev Multiplies a proper fraction by integer, the resulting integer is rounded down
* @param f a fraction
* @param by an integer to multiply fraction by
* @return result of multiplication `f * by`
*/
function multiplyByInteger(uint16 f, uint256 by) internal pure returns(uint256) {
// extract nominator and denominator
uint8 nominator = getNominator(f);
uint8 denominator = getDenominator(f);
// for a fraction representing one just return `by`
if(nominator == denominator) {
// the result of multiplication by one is the value itself
return by;
}
// next section of code is for proper fractions only
require(nominator < denominator);
// for values small enough multiplication is straight forward
if(by == uint240(by)) {
// ensure the maximum precision of calculation
return by * nominator / denominator;
}
// for big values we perform division first, loosing the precision
return by / denominator * nominator;
}
}
/**
* @notice Country is unique tradable entity. Non-fungible.
* @dev A country is an ERC721 non-fungible token, which maps Token ID,
* a 8 bit number in range [1, 192] to a set of country properties -
* number of plots and owner's tax rate.
* @dev Country token supports only minting of predefined countries,
* its not possible to destroy a country.
* @dev Up to 192 countries are defined during contract deployment and initialization.
*/
contract CountryERC721 is AccessControl, ERC165 {
/// @dev Using library Fractions for fraction math
using Fractions16 for uint16;
/// @dev Smart contract version
/// @dev Should be incremented manually in this source code
/// each time smart contact source code is changed
uint32 public constant TOKEN_VERSION = 0x1;
/// @dev ERC20 compliant token symbol
string public constant symbol = "CTY";
/// @dev ERC20 compliant token name
string public constant name = "Country – CryptoMiner World";
/// @dev ERC20 compliant token decimals
/// @dev this can be only zero, since ERC721 token is non-fungible
uint8 public constant decimals = 0;
/// @dev Country data structure
/// @dev Occupies 1 storage slot (240 bits)
struct Country {
/// @dev Unique country ID ∈ [1, 192]
uint8 id;
/// @dev Number of land plots country has,
/// proportional to the country area
uint16 plots;
/// @dev Percentage country owner receives from each sale
uint16 tax;
/// @dev Tax modified time - unix timestamp
uint32 taxModified;
/// @dev Country index within an owner's collection of countries
uint8 index;
/// @dev Country owner, initialized upon country creation
address owner;
}
/// @dev Country data array contains number of plots each country contains
uint16[] public countryData;
/// @notice All the existing countries
/// @dev Core of the Country as ERC721 token
/// @dev Maps Country ID => Country Data Structure
mapping(uint256 => Country) public countries;
/// @dev Mapping from a token ID to an address approved to
/// transfer ownership rights for this token
mapping(uint256 => address) public approvals;
/// @dev Mapping from owner to operator approvals
/// token owner => approved token operator => is approved
mapping(address => mapping(address => bool)) public approvedOperators;
/// @notice Storage for a collections of tokens
/// @notice A collection of tokens is an unordered list of token IDs,
/// owned by a particular address (owner)
/// @dev A mapping from owner to a collection of his tokens (IDs)
/// @dev ERC20 compliant structure for balances can be derived
/// as a length of each collection in the mapping
/// @dev ERC20 balances[owner] is equal to collections[owner].length
mapping(address => uint8[]) public collections;
/// @dev Array with all token ids, used for enumeration
/// @dev ERC20 compliant structure for totalSupply can be derived
/// as a length of this collection
/// @dev ERC20 totalSupply() is equal to allTokens.length
uint8[] public allTokens;
/// @dev Total number of countries this smart contract holds
uint8 private _totalSupply;
/// @dev Token bitmap – bitmap of 192 elements indicating existing (minted) tokens
/// @dev For any i ∈ [0, 191] - tokenMap[i] (which is tokenMap >> i & 0x1)
/// is equal to one if token with ID i exists and to zero if it doesn't
uint192 public tokenMap;
/// @notice The maximum frequency at which tax rate for a token can be changed
/// @dev Tax rate cannot be changed more frequently than once per `MAX_TAX_CHANGE_FREQ` seconds
uint32 public maxTaxChangeFreq = 86400; // seconds
/// @dev Maximum tokens allowed should comply with the `tokenMap` type
/// @dev This setting is used only in contract constructor, actual
/// maximum supply is defined by `countryData` array length
uint8 public constant TOTAL_SUPPLY_MAX = 192;
/// @notice Maximum tax rate that can be set on the country
/// @dev This is an inverted value of the maximum tax:
/// `MAX_TAX_RATE = 1 / MAX_TAX_INV`
uint8 public constant MAX_TAX_INV = 5; // 1/5 or 20%
/// @notice Default tax rate that is assigned to each country
/// @dev This tax rate is set on each country when minting its token
uint16 public constant DEFAULT_TAX_RATE = 0x010A; // 1/10 or 10%
/// @dev Enables ERC721 transfers of the tokens
uint32 public constant FEATURE_TRANSFERS = 0x00000001;
/// @dev Enables ERC721 transfers on behalf
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x00000002;
/// @dev Allows owners to update tax value
uint32 public constant FEATURE_ALLOW_TAX_UPDATE = 0x00000004;
/// @notice Tax manager is responsible for updating maximum
/// allowed frequency of tax rate change
/// @dev Role ROLE_TAX_MANAGER allows updating `maxTaxChangeFreq`
uint32 public constant ROLE_TAX_MANAGER = 0x00020000;
/// @notice Token creator is responsible for creating tokens
/// @dev Role ROLE_TOKEN_CREATOR allows minting tokens
uint32 public constant ROLE_TOKEN_CREATOR = 0x00040000;
/// @dev Magic value to be returned upon successful reception of an NFT
/// @dev Equal to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
/// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
/**
* Supported interfaces section
*/
/**
* ERC721 interface definition in terms of ERC165
*
* 0x80ac58cd ==
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/**
* ERC721 interface extension – exists(uint256)
*
* 0x4f558e79 == bytes4(keccak256('exists(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/**
* ERC721 interface extension - ERC721Enumerable
*
* 0x780e9d63 ==
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* ERC721 interface extension - ERC721Metadata
*
* 0x5b5e139f ==
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/// @dev Event names are self-explanatory:
/// @dev Fired in mint()
/// @dev Address `_by` allows to track who created a token
event Minted(address indexed _by, address indexed _to, uint8 indexed _tokenId);
/// @dev Fired in transfer(), transferFor(), mint()
/// @dev When minting a token, address `_from` is zero
/// @dev ERC20/ERC721 compliant event
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId, uint256 _value);
/// @dev Fired in approve()
/// @dev ERC721 compliant event
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev Fired in setApprovalForAll()
/// @dev ERC721 compliant event
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _value);
/// @dev Fired in updateTaxRate()
event TaxRateUpdated(address indexed _owner, uint256 indexed _tokenId, uint16 tax, uint16 oldTax);
/**
* @dev Creates a Country ERC721 instance,
* @dev Registers a ERC721 interface using ERC165
* @dev Initializes the contract with the country data provided
* @param _countryData array of packed data structures containing
* number of plots for each country
*/
constructor(uint16[] _countryData) public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
// maximum of 192 countries allowed
require(_countryData.length <= TOTAL_SUPPLY_MAX);
// init country data array
countryData = _countryData;
}
/**
* @notice Number of countries this contract can have
* @dev Maximum number of tokens that contract can mint
* @return length of country data array
*/
function getNumberOfCountries() public constant returns(uint8) {
// read country data array length and return
return uint8(countryData.length);
}
/**
* @dev Calculates cumulative number of plots all the countries have in total
* @return sum of the countries number of plots
*/
function getTotalNumberOfPlots() public constant returns(uint32) {
// variable to accumulate result into
uint32 result = 0;
// iterate over all the tokens and accumulate the result
for(uint i = 0; i < countryData.length; i++) {
// accumulate the result
result += countryData[i];
}
// return the result
return result;
}
/**
* @dev Calculates cumulative number of plots
* all the countries belonging to given owner have in total
* @param owner address of the owner to query countries for
* @return sum of the countries number of plots owned by given address
*/
function getNumberOfPlotsByCountryOwner(address owner) public constant returns(uint32) {
// variable to accumulate result into
uint32 result = 0;
// iterate over all owner's tokens and accumulate the result
for(uint i = 0; i < collections[owner].length; i++) {
// accumulate the result
result += countries[collections[owner][i]].plots;
}
// return the result
return result;
}
/**
* @dev Gets a country by ID, representing it as a single 32-bit integer.
* The integer is tightly packed with the country data:
* number of plots
* tax nominator
* tax denominator
* @dev Throws if country doesn't exist
* @param _tokenId ID of the country to fetch
* @return country as 32-bit unsigned integer
*/
function getPacked(uint256 _tokenId) public constant returns(uint32) {
// validate country existence
require(exists(_tokenId));
// load country from storage
Country memory country = countries[_tokenId];
// pack the data and return
return uint32(country.plots) << 16 | country.tax;
}
/**
* @notice Retrieves a collection of tokens owned by a particular address
* @notice An order of token IDs is not guaranteed and may change
* when a token from the list is transferred
* @param owner an address to query a collection for
* @return an unordered list of token IDs owned by given address
*/
function getCollection(address owner) public constant returns(uint8[]) {
// read a collection from mapping and return
return collections[owner];
}
/**
* @dev Allows to fetch collection of tokens, including internal token data
* in a single function, useful when connecting to external node like INFURA
* @dev Each element of the array returned is a tightly packed integer, containing
* token ID
* number of plots
* tax nominator
* tax denominator
* @param owner an address to query a collection for
* @return an unordered list of country packed data owned by give address
*/
function getPackedCollection(address owner) public constant returns(uint40[]) {
// get the list of token IDs the owner owns
uint8[] memory ids = getCollection(owner);
// allocate correspondent array for packed data
uint40[] memory packedCollection = new uint40[](ids.length);
// fetch token info one by one and pack it into the structure
for(uint i = 0; i < ids.length; i++) {
// token ID
uint8 tokenId = ids[i];
// packed token data
uint32 packedData = getPacked(tokenId);
// pack the data and save it into result array
packedCollection[i] = uint40(tokenId) << 32 | packedData;
}
// return the result (it can be empty array as well)
return packedCollection;
}
/**
* @notice Returns number of plots for the given country, defined by `_tokenId`
* @param _tokenId country id to query number of plots for
* @return number of plots given country has
*/
function getNumberOfPlots(uint256 _tokenId) public constant returns(uint16) {
// validate token existence
require(exists(_tokenId));
// obtain token's number of plots from storage and return
return countries[_tokenId].plots;
}
/**
* @notice Returns tax as a proper fraction for the given country, defined by `_tokenId`
* @param _tokenId country id to query tax for
* @return tax as a proper fraction (tuple containing nominator and denominator)
*/
function getTax(uint256 _tokenId) public constant returns(uint8, uint8) {
// obtain token's tax as packed fraction
uint16 tax = getTaxPacked(_tokenId);
// return tax as a proper fraction
return (tax.getNominator(), tax.getDenominator());
}
/**
* @notice Returns tax as a proper fraction for the given country, defined by `_tokenId`
* @param _tokenId country id to query tax for
* @return tax as a proper fraction packed into uint16
*/
function getTaxPacked(uint256 _tokenId) public constant returns(uint16) {
// validate token existence
require(exists(_tokenId));
// obtain token's tax from storage and return tax
return countries[_tokenId].tax;
}
/**
* @notice Returns tax percent for the given country, defined by `_tokenId`
* @dev Converts 16-bit fraction structure into 8-bit [0, 100] percent value
* @param _tokenId country id to query tax for
* @return tax percent value, [0, 100]
*/
function getTaxPercent(uint256 _tokenId) public constant returns (uint8) {
// validate token existence
require(exists(_tokenId));
// obtain token's tax percent from storage and return
return countries[_tokenId].tax.toPercent();
}
/**
* @notice Calculates tax value for the given token and value
* @param _tokenId token id to use tax rate from
* @param _value an amount to apply tax to
* @return calculated tax value based on the tokens tax rate and value
*/
function calculateTaxValueFor(uint256 _tokenId, uint256 _value) public constant returns (uint256) {
// validate token existence
require(exists(_tokenId));
// obtain token's tax percent from storage, multiply by value and return
return countries[_tokenId].tax.multiplyByInteger(_value);
}
/**
* @notice Allows token owner to update tax rate of the country this token represents
* @dev Requires tax update feature to be enabled on the contract
* @dev Requires message sender to be owner of the token
* @dev Requires previous tax change to be more then `maxTaxChangeFreq` blocks ago
* @param _tokenId country id to update tax for
* @param nominator tax rate nominator
* @param denominator tax rate denominator
*/
function updateTaxRate(uint256 _tokenId, uint8 nominator, uint8 denominator) public {
// check if tax updating is enabled
require(__isFeatureEnabled(FEATURE_ALLOW_TAX_UPDATE));
// check that sender is token owner, ensures also that token exists
require(msg.sender == ownerOf(_tokenId));
// check that tax rate doesn't exceed MAX_TAX_RATE
require(nominator <= denominator / MAX_TAX_INV);
// check that enough time has passed since last tax update
require(countries[_tokenId].taxModified + maxTaxChangeFreq <= now);
// save old tax value to log
uint16 oldTax = countries[_tokenId].tax;
// update the tax rate
countries[_tokenId].tax = Fractions16.createProperFraction16(nominator, denominator);
// update tax rate updated timestamp
countries[_tokenId].taxModified = uint32(now);
// emit an event
emit TaxRateUpdated(msg.sender, _tokenId, countries[_tokenId].tax, oldTax);
}
/**
* @dev Allows setting the `maxTaxChangeFreq` parameter of the contract,
* which specifies how frequently the tax rate can be changed
* @dev Requires sender to have `ROLE_TAX_MANAGER` permission.
* @param _maxTaxChangeFreq a value to set `maxTaxChangeFreq` to
*/
function updateMaxTaxChangeFreq(uint32 _maxTaxChangeFreq) public {
// check if caller has sufficient permissions to update tax change frequency
require(__isSenderInRole(ROLE_TAX_MANAGER));
// update the tax change frequency
maxTaxChangeFreq = _maxTaxChangeFreq;
}
/**
* @dev Creates new token with `tokenId` ID specified and
* assigns an ownership `to` for that token
* @dev Initial token's properties are predefined by its ID
* @param to an address to assign created token ownership to
* @param tokenId ID of the token to create
*/
function mint(address to, uint8 tokenId) public {
// validate destination address
require(to != address(0));
require(to != address(this));
// check if caller has sufficient permissions to mint a token
require(__isSenderInRole(ROLE_TOKEN_CREATOR));
// delegate call to `__mint`
__mint(to, tokenId);
// fire Minted event
emit Minted(msg.sender, to, tokenId);
// fire ERC20/ERC721 transfer event
emit Transfer(address(0), to, tokenId, 1);
}
/**
* @notice Total number of existing tokens (tracked by this contract)
* @return A count of valid tokens tracked by this contract,
* where each one of them has an assigned and
* queryable owner not equal to the zero address
*/
function totalSupply() public constant returns (uint256) {
// read the length of the `allTokens` collection
return allTokens.length;
}
/**
* @notice Enumerate valid tokens
* @dev Throws if `_index` >= `totalSupply()`.
* @param _index a counter less than `totalSupply()`
* @return The token ID for the `_index`th token, unsorted
*/
function tokenByIndex(uint256 _index) public constant returns (uint256) {
// out of bounds check
require(_index < allTokens.length);
// get the token ID and return
return allTokens[_index];
}
/**
* @notice Enumerate tokens assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)`.
* @param _owner an address of the owner to query token from
* @param _index a counter less than `balanceOf(_owner)`
* @return the token ID for the `_index`th token assigned to `_owner`, unsorted
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256) {
// out of bounds check
require(_index < collections[_owner].length);
// get the token ID from owner collection and return
return collections[_owner][_index];
}
/**
* @notice Gets an amount of token owned by the given address
* @dev Gets the balance of the specified address
* @param _owner address to query the balance for
* @return an amount owned by the address passed as an input parameter
*/
function balanceOf(address _owner) public constant returns (uint256) {
// validate an owner address
require(_owner != address(0));
// read the length of the `who`s collection of tokens
return collections[_owner].length;
}
/**
* @notice Checks if specified token exists
* @dev Returns whether the specified token ID exists
* @param _tokenId ID of the token to query the existence for
* @return whether the token exists (true - exists)
*/
function exists(uint256 _tokenId) public constant returns (bool) {
// check if this token exists (owner is not zero)
return countries[_tokenId].owner != address(0);
}
/**
* @notice Finds an owner address for a token specified
* @dev Gets the owner of the specified token from the `countries` mapping
* @dev Throws if a token with the ID specified doesn't exist
* @param _tokenId ID of the token to query the owner for
* @return owner address currently marked as the owner of the given token
*/
function ownerOf(uint256 _tokenId) public constant returns (address) {
// check if this token exists
require(exists(_tokenId));
// return owner's address
return countries[_tokenId].owner;
}
/**
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @dev Requires the sender of the transaction to be an owner
* of the token specified (`tokenId`)
* @param to new owner address
* @param _tokenId ID of the token to transfer ownership rights for
*/
function transfer(address to, uint256 _tokenId) public {
// check if token transfers feature is enabled
require(__isFeatureEnabled(FEATURE_TRANSFERS));
// call sender gracefully - `from`
address from = msg.sender;
// delegate call to unsafe `__transfer`
__transfer(from, to, _tokenId);
}
/**
* @notice A.k.a "transfer a token on behalf"
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @notice Allows transferring ownership rights by a trading operator
* on behalf of token owner. Allows building an exchange of tokens.
* @dev Transfers the ownership of a given token ID to another address
* @dev Requires the transaction sender to be one of:
* owner of a token - then its just a usual `transfer`
* approved – an address explicitly approved earlier by
* the owner of a token to transfer this particular token `tokenId`
* operator - an address explicitly approved earlier by
* the owner to transfer all his tokens on behalf
* @param _from current owner of the token
* @param _to address to receive the ownership of the token
* @param _tokenId ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == msg.sender && __isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != msg.sender && __isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF));
// call sender gracefully - `operator`
address operator = msg.sender;
// find if an approved address exists for this token
address approved = approvals[_tokenId];
// we assume `from` is an owner of the token,
// this will be explicitly checked in `__transfer`
// fetch how much approvals left for an operator
bool approvedOperator = approvedOperators[_from][operator];
// operator must have an approval to transfer this particular token
// or operator must be approved to transfer all the tokens
// or, if nothing satisfies, this is equal to regular transfer,
// where `from` is basically a transaction sender and owner of the token
if(operator != approved && !approvedOperator) {
// transaction sender doesn't have any special permissions
// we will treat him as a token owner and sender and try to perform
// a regular transfer:
// check `from` to be `operator` (transaction sender):
require(_from == operator);
}
// delegate call to unsafe `__transfer`
__transfer(_from, _to, _tokenId);
}
/**
* @notice A.k.a "safe transfer a token on behalf"
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @notice Allows transferring ownership rights by a trading operator
* on behalf of token owner. Allows building an exchange of tokens.
* @dev Safely transfers the ownership of a given token ID to another address
* @dev Requires the transaction sender to be the owner, approved, or operator
* @dev When transfer is complete, this function
* checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
* @param _from current owner of the token
* @param _to address to receive the ownership of the token
* @param _tokenId ID of the token to be transferred
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public {
// delegate call to usual (unsafe) `transferFrom`
transferFrom(_from, _to, _tokenId);
// check if receiver `_to` supports ERC721 interface
if (AddressUtils.isContract(_to)) {
// if `_to` is a contract – execute onERC721Received
bytes4 response = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
// expected response is ERC721_RECEIVED
require(response == ERC721_RECEIVED);
}
}
/**
* @notice A.k.a "safe transfer a token on behalf"
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @notice Allows transferring ownership rights by a trading operator
* on behalf of token owner. Allows building an exchange of tokens.
* @dev Safely transfers the ownership of a given token ID to another address
* @dev Requires the transaction sender to be the owner, approved, or operator
* @dev Requires from to be an owner of the token
* @dev 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,uint256,bytes)"))`;
* otherwise the transfer is reverted.
* @dev This works identically to the other function with an extra data parameter,
* except this function just sets data to "".
* @param _from current owner of the token
* @param _to address to receive the ownership of the token
* @param _tokenId ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
// delegate call to overloaded `safeTransferFrom`, set data to ""
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice Approves an address to transfer the given token on behalf of its owner
* Can also be used to revoke an approval by setting `to` address to zero
* @dev The zero `to` address revokes an approval for a given token
* @dev There can only be one approved address per token at a given time
* @dev This function can only be called by the token owner
* @param _approved address to be approved to transfer the token on behalf of its owner
* @param _tokenId ID of the token to be approved for transfer on behalf
*/
function approve(address _approved, uint256 _tokenId) public {
// call sender nicely - `from`
address from = msg.sender;
// get token owner address (also ensures that token exists)
address owner = ownerOf(_tokenId);
// caller must own this token
require(from == owner);
// approval for owner himself is pointless, do not allow
require(_approved != owner);
// either we're removing approval, or setting it
require(approvals[_tokenId] != address(0) || _approved != address(0));
// set an approval (deletes an approval if to == 0)
approvals[_tokenId] = _approved;
// emit an ERC721 event
emit Approval(from, _approved, _tokenId);
}
/**
* @notice Removes an approved address, which was previously added by `approve`
* for the given token. Equivalent to calling approve(0, tokenId)
* @dev Same as calling approve(0, tokenId)
* @param _tokenId ID of the token to remove approved address for
*/
function revokeApproval(uint256 _tokenId) public {
// delegate call to `approve`
approve(address(0), _tokenId);
}
/**
* @dev 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 to operator address to set the approval for
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
// call sender nicely - `from`
address from = msg.sender;
// validate destination address
require(to != address(0));
// approval for owner himself is pointless, do not allow
require(to != from);
// set an approval
approvedOperators[from][to] = approved;
// emit an ERC721 compliant event
emit ApprovalForAll(from, to, approved);
}
/**
* @notice Get the approved address for a single token
* @dev Throws if `_tokenId` is not a valid token ID.
* @param _tokenId ID of the token to find the approved address for
* @return the approved address for this token, or the zero address if there is none
*/
function getApproved(uint256 _tokenId) public constant returns (address) {
// validate token existence
require(exists(_tokenId));
// find approved address and return
return approvals[_tokenId];
}
/**
* @notice Query if an address is an authorized operator for another address
* @param _owner the address that owns at least one token
* @param _operator the address that acts on behalf of the owner
* @return true if `_operator` is an approved operator for `_owner`, false otherwise
*/
function isApprovedForAll(address _owner, address _operator) public constant returns (bool) {
// is there a positive amount of approvals left
return approvedOperators[_owner][_operator];
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev Throws if `_tokenId` is not a valid token ID.
* URIs are defined in RFC 3986.
* @param _tokenId uint256 ID of the token to query
* @return token URI
*/
function tokenURI(uint256 _tokenId) public constant returns (string) {
// validate token existence
require(exists(_tokenId));
// token URL consists of base URL part (domain) and token ID
return StringUtils.concat("http://cryptominerworld.com/country/", StringUtils.itoa(_tokenId, 10));
}
/// @dev Performs a transfer of a token `tokenId` from address `from` to address `to`
/// @dev Unsafe: doesn't check if caller has enough permissions to execute the call;
/// checks only for token existence and that ownership belongs to `from`
/// @dev Is save to call from `transfer(to, tokenId)` since it doesn't need any additional checks
/// @dev Must be kept private at all times
function __transfer(address from, address to, uint256 _tokenId) private {
// validate source and destination address
require(to != address(0));
require(to != from);
// impossible by design of transfer(), transferFrom(),
// approveToken() and approve()
assert(from != address(0));
// validate token existence
require(exists(_tokenId));
// validate token ownership
require(ownerOf(_tokenId) == from);
// clear approved address for this particular token + emit event
__clearApprovalFor(_tokenId);
// move token ownership,
// update old and new owner's token collections accordingly
__move(from, to, _tokenId);
// fire ERC20/ERC721 transfer event
emit Transfer(from, to, _tokenId, 1);
}
/// @dev Clears approved address for a particular token
function __clearApprovalFor(uint256 _tokenId) private {
// check if approval exists - we don't want to fire an event in vain
if(approvals[_tokenId] != address(0)) {
// clear approval
delete approvals[_tokenId];
// emit an ERC721 event
emit Approval(msg.sender, address(0), _tokenId);
}
}
/// @dev Move `country` from owner `from` to a new owner `to`
/// @dev Unsafe, doesn't check for consistence
/// @dev Must be kept private at all times
function __move(address from, address to, uint256 _tokenId) private {
// cast token ID to uint32 space
uint8 tokenId = uint8(_tokenId);
// overflow check, failure impossible by design of mint()
assert(tokenId == _tokenId);
// get the country pointer to the storage
Country storage country = countries[_tokenId];
// get a reference to the collection where country is now
uint8[] storage source = collections[from];
// get a reference to the collection where country goes to
uint8[] storage destination = collections[to];
// collection `source` cannot be empty, if it is - it's a bug
assert(source.length != 0);
// index of the country within collection `source`
uint8 i = country.index;
// we put the last country in the collection `source` to the position released
// get an ID of the last country in `source`
uint8 sourceId = source[source.length - 1];
// update country index to point to proper place in the collection `source`
countries[sourceId].index = i;
// put it into the position i within `source`
source[i] = sourceId;
// trim the collection `source` by removing last element
source.length--;
// update country index according to position in new collection `destination`
country.index = uint8(destination.length);
// update country owner
country.owner = to;
// push country into collection
destination.push(tokenId);
}
/// @dev Creates new token with `tokenId` ID specified and
/// assigns an ownership `to` for this token
/// @dev Unsafe: doesn't check if caller has enough permissions to execute the call
/// checks only that the token doesn't exist yet
/// @dev Must be kept private at all times
function __mint(address to, uint8 tokenId) private {
// check that `tokenId` is inside valid bounds
require(tokenId > 0 && tokenId <= countryData.length);
// ensure that token with such ID doesn't exist
require(!exists(tokenId));
// create new country in memory
Country memory country = Country({
id: tokenId,
plots: countryData[tokenId - 1],
tax: DEFAULT_TAX_RATE,
taxModified: 0,
index: uint8(collections[to].length),
owner: to
});
// push newly created `tokenId` to the owner's collection of tokens
collections[to].push(tokenId);
// persist country to the storage
countries[tokenId] = country;
// add token ID to the `allTokens` collection,
// automatically updates total supply
allTokens.push(tokenId);
// update token bitmap
tokenMap |= uint192(1 << uint256(tokenId - 1));
}
}
|
Creates proper fraction with nominator < denominator Throws if nominator is equal or greater then denominator Throws if denominator is zero n fraction nominator d fraction denominator return fraction with nominator and denominator specified/ denominator cannot be zero by the definition of division fraction has to be proper construct fraction and return
|
function createProperFraction16(uint8 n, uint8 d) internal pure returns (uint16) {
require(d != 0);
require(n < d);
return uint16(n) << 8 | d;
}
| 6,443,042
|
./full_match/42/0x290883B56C1d14936b3c99866d810A6Aab7a121C/sources/Users/225153/Projects/ram/contracts/Governance.sol
|
1 day mandatory wait time after last router regenerator tax update
|
function enterRegeneratorUpdateStagingMode() public {
require(block.timestamp >= lastRAMRouterUpdateTime.add(1 days), "Must wait 1 day since last update");
updateStagingMode = true;
updateStagingReadyTime = block.timestamp.add(10 minutes);
}
| 16,233,673
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../infiniteProxy/proxy.sol";
contract InstaVault is Proxy {
constructor(address admin_, address dummyImplementation_)
Proxy(admin_, dummyImplementation_)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./events.sol";
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`.
*/
contract Internals is Events {
struct AddressSlot {
address value;
}
struct SigsSlot {
bytes4[] value;
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Storage slot with the address of the current dummy-implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _DUMMY_IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _getSlotImplSigsSlot(address implementation_)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode("eip1967.proxy.implementation", implementation_)
);
}
function _getSlotSigsImplSlot(bytes4 sig_) internal pure returns (bytes32) {
return keccak256(abi.encode("eip1967.proxy.implementation", sig_));
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot_)
internal
pure
returns (AddressSlot storage _r)
{
assembly {
_r.slot := slot_
}
}
/**
* @dev Returns an `SigsSlot` with member `value` located at `slot`.
*/
function getSigsSlot(bytes32 slot_)
internal
pure
returns (SigsSlot storage _r)
{
assembly {
_r.slot := slot_
}
}
/**
* @dev Sets new implementation and adds mapping from implementation to sigs and sig to implementation.
*/
function _setImplementationSigs(
address implementation_,
bytes4[] memory sigs_
) internal {
require(sigs_.length != 0, "no-sigs");
bytes32 slot_ = _getSlotImplSigsSlot(implementation_);
bytes4[] memory sigsCheck_ = getSigsSlot(slot_).value;
require(sigsCheck_.length == 0, "implementation-already-exist");
for (uint256 i = 0; i < sigs_.length; i++) {
bytes32 sigSlot_ = _getSlotSigsImplSlot(sigs_[i]);
require(
getAddressSlot(sigSlot_).value == address(0),
"sig-already-exist"
);
getAddressSlot(sigSlot_).value = implementation_;
}
getSigsSlot(slot_).value = sigs_;
emit setImplementationLog(implementation_, sigs_);
}
/**
* @dev removes implementation and the mappings corresponding to it.
*/
function _removeImplementationSigs(address implementation_) internal {
bytes32 slot_ = _getSlotImplSigsSlot(implementation_);
bytes4[] memory sigs_ = getSigsSlot(slot_).value;
require(sigs_.length != 0, "implementation-not-exist");
for (uint256 i = 0; i < sigs_.length; i++) {
bytes32 sigSlot_ = _getSlotSigsImplSlot(sigs_[i]);
delete getAddressSlot(sigSlot_).value;
}
delete getSigsSlot(slot_).value;
emit removeImplementationLog(implementation_);
}
function _getImplementationSigs(address implementation_)
internal
view
returns (bytes4[] memory)
{
bytes32 slot_ = _getSlotImplSigsSlot(implementation_);
return getSigsSlot(slot_).value;
}
function _getSigImplementation(bytes4 sig_)
internal
view
returns (address implementation_)
{
bytes32 slot_ = _getSlotSigsImplSlot(sig_);
return getAddressSlot(slot_).value;
}
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Returns the current dummy-implementation.
*/
function _getDummyImplementation() internal view returns (address) {
return getAddressSlot(_DUMMY_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin_) internal {
address oldAdmin_ = _getAdmin();
require(
newAdmin_ != address(0),
"ERC1967: new admin is the zero address"
);
getAddressSlot(_ADMIN_SLOT).value = newAdmin_;
emit setAdminLog(oldAdmin_, newAdmin_);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setDummyImplementation(address newDummyImplementation_) internal {
address oldDummyImplementation_ = _getDummyImplementation();
getAddressSlot(_DUMMY_IMPLEMENTATION_SLOT)
.value = newDummyImplementation_;
emit setDummyImplementationLog(
oldDummyImplementation_,
newDummyImplementation_
);
}
/**
* @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 {
// 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 Delegates the current call to the address returned by Implementations registry.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback(bytes4 sig_) internal {
address implementation_ = _getSigImplementation(sig_);
require(
implementation_ != address(0),
"Liquidity: Not able to find implementation_"
);
_delegate(implementation_);
}
}
contract AdminStuff is Internals {
modifier onlyAdmin() {
require(msg.sender == _getAdmin(), "not-the-admin");
_;
}
/**
* @dev sets new admin.
*/
function setAdmin(address newAdmin_) external onlyAdmin {
_setAdmin(newAdmin_);
}
/**
* @dev sets new dummy-implementation.
*/
function setDummyImplementation(address newDummyImplementation_)
external
onlyAdmin
{
_setDummyImplementation(newDummyImplementation_);
}
/**
* @dev adds new implementation address.
*/
function addImplementation(address implementation_, bytes4[] calldata sigs_)
external
onlyAdmin
{
_setImplementationSigs(implementation_, sigs_);
}
/**
* @dev removes an existing implementation address.
*/
function removeImplementation(address implementation_) external onlyAdmin {
_removeImplementationSigs(implementation_);
}
constructor(address admin_, address dummyImplementation_) {
_setAdmin(admin_);
_setDummyImplementation(dummyImplementation_);
}
}
abstract contract Proxy is AdminStuff {
constructor(address admin_, address dummyImplementation_)
AdminStuff(admin_, dummyImplementation_)
{}
/**
* @dev returns admin's address.
*/
function getAdmin() external view returns (address) {
return _getAdmin();
}
/**
* @dev returns dummy-implementations's address.
*/
function getDummyImplementation() external view returns (address) {
return _getDummyImplementation();
}
/**
* @dev returns bytes4[] sigs from implementation address If not registered then returns empty array.
*/
function getImplementationSigs(address impl_)
external
view
returns (bytes4[] memory)
{
return _getImplementationSigs(impl_);
}
/**
* @dev returns implementation address from bytes4 sig. If sig is not registered then returns address(0).
*/
function getSigsImplementation(bytes4 sig_)
external
view
returns (address)
{
return _getSigImplementation(sig_);
}
/**
* @dev Fallback function that delegates calls to the address returned by Implementations registry.
*/
fallback() external payable {
_fallback(msg.sig);
}
/**
* @dev Fallback function that delegates calls to the address returned by Implementations registry.
*/
receive() external payable {
if (msg.sig != 0x00000000) {
_fallback(msg.sig);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Events {
event setAdminLog(address oldAdmin_, address newAdmin_);
event setDummyImplementationLog(
address oldDummyImplementation_,
address newDummyImplementation_
);
event setImplementationLog(address implementation_, bytes4[] sigs_);
event removeImplementationLog(address implementation_);
}
|
sets new admin./
|
function setAdmin(address newAdmin_) external onlyAdmin {
_setAdmin(newAdmin_);
}
| 6,230,835
|
./full_match/3/0xEd015673D365D4275ffd08D677397DC0444773E0/sources/tmp.sol
|
------------------------------------------------------------------------ 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_1, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to_1] = safeAdd(balances[to_1], tokens);
emit Transfer(from, to_1, tokens);
return true;
}
| 8,265,489
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @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 v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/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/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: ERC721A.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* 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 = 0;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `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_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(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)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - 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
) internal virtual {
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 private nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > 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 {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/FungibleFeet.sol
pragma solidity ^0.8.0;
contract FungibleFeet is ERC721A, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
uint256 public cost = 0.011 ether;
uint256 public maxSupply = 4444;
uint256 public setMaxMintAmountPerTxn = 20;
uint256 public maxMintAmountPerWallet = 50;
uint256 public totalPresaleTickets = 0;
uint256 public reserve = 2;
uint256 public reserveMinted = 0;
bool public paused = true;
bool public revealed = false;
bool public startMainSale = false;
mapping(address => bool) private _presaleList;
mapping(address => bool) private _giftFreeMint;
mapping(address => uint256) public _totalMintedPresale;
mapping(address => uint256) public _totalMintedMainsale;
constructor() ERC721A("FungibleFeet", "FF", maxSupply, maxSupply) {
setBaseURI("ipfs://.../");
setNotRevealedURI("ipfs://QmXVSt1mFXTati5jCK4cYF3xPEmxrWNPfLGBKPp74QjcMG/hidden.json");
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// This function is for Premint sale
function preSaleMint(uint256 _mintAmount) public payable {
if (msg.sender != owner()){
require(!paused, "Public sale is not live, can't mint");
require(_presaleList[msg.sender] == true,"You're not on the whitelist");
require(_mintAmount <= maxMintAmountPerWallet, "Max Mint amount per session exceeded");
}
require(_mintAmount > 0, "Need to mint atleast 1 FF");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded");
require(supply + _mintAmount <= totalPresaleTickets, "Limit exceeded for presale");
require(_totalMintedPresale[msg.sender] + _mintAmount <= maxMintAmountPerWallet,
"exceeded presale total mints per wallet");
if (msg.sender != owner()) {
// checking if user have free mint available
if (_giftFreeMint[msg.sender]==false){
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
else{
require(_mintAmount == 1, "You can only 1 free mint");
_giftFreeMint[msg.sender]=false;
}
}
// minting presale NFT
_totalMintedPresale[msg.sender] = _totalMintedPresale[msg.sender] + _mintAmount;
_safeMint(msg.sender, _mintAmount);
}
// This function will add users to presale listing
function addToPresaleListing(address[] calldata _addresses)
external
onlyOwner
{
for (uint256 index = 0; index < _addresses.length; index++) {
require(_addresses[index] != address(0),"Can't add a zero address");
if (_presaleList[_addresses[index]] == false) {
_presaleList[_addresses[index]] = true;
}
}
}
// This function will be used to remove user from presale listing
function removeFromPresaleListing(address[] calldata _addresses)
external
onlyOwner
{
for (uint256 ind = 0; ind < _addresses.length; ind++) {
require(_addresses[ind] != address(0),"Can't remove a zero address");
if (_presaleList[_addresses[ind]] == true) {
_presaleList[_addresses[ind]] = false;
}
}
}
// function will be check if user is eligible for presale
function checkIsOnPresaleList(address _address) external view returns (bool) {
return _presaleList[_address];
}
// function will be check if user is eligible for freemint
function checkIsOnFreesaleList(address _address) external view returns (bool) {
return _giftFreeMint[_address];
}
// This function will be used for Main sale
function saleMint(uint256 _mintAmount) public payable {
if (msg.sender != owner()){
require(!paused, "Public sale is not live, can't mint");
require(_mintAmount <= setMaxMintAmountPerTxn, "Max Mint amount exceeded");
require(startMainSale == true, "Main sale is not started yet");
}
require(_mintAmount > 0, "Need to mint at least 1 FF");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded");
require(
_totalMintedMainsale[msg.sender] + _mintAmount <= maxMintAmountPerWallet,
"exceeded presale total mints per wallet"
);
if (msg.sender != owner()) {
if (_giftFreeMint[msg.sender]==false){
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
else{
require(_mintAmount == 1, "You can only 1 free mint");
_giftFreeMint[msg.sender]=false;
}
}
_safeMint(msg.sender, _mintAmount);
}
// Function for minting the reserve NFTs for owner
function reserveNFTs(uint256 amount) public onlyOwner{
require(reserveMinted + amount <= reserve, "Max NFT limit reservation exceeded");
_safeMint(msg.sender, amount);
reserveMinted = reserveMinted + amount;
}
// function to get the total NFTs by one address
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
// function will add user to free mint
function addToFreeMint(address[] calldata _addresses) external onlyOwner {
for (uint256 index = 0; index < _addresses.length; index++) {
require(
_addresses[index] != address(0),
"Can't add a zero address"
);
if (_giftFreeMint[_addresses[index]] == false) {
_giftFreeMint[_addresses[index]] = true;
}
}
}
// Removing user from the free mint
function removeFromFreeMint(address[] calldata _addresses)
external
onlyOwner
{
for (uint256 index = 0; index < _addresses.length; index++) {
require(
_addresses[index] != address(0),
"Can't remove a zero address"
);
if (_giftFreeMint[_addresses[index]] == true) {
_giftFreeMint[_addresses[index]] = false;
}
}
}
// for revealing the NFTs
function revertReveal() public onlyOwner() {
revealed = !revealed;
}
function revertStartMainSale() public onlyOwner{
startMainSale = !startMainSale;
}
function setMaxMintAmountPerWallet(uint256 _limit) public onlyOwner() {
maxMintAmountPerWallet = _limit;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setReserve(uint256 _reserve) public onlyOwner(){
reserve = _reserve;
}
// function to update the presale NFT amount
function setTotalPresaleQuantity( uint256 _totalPresaleTickets) public onlyOwner(){
totalPresaleTickets = _totalPresaleTickets;
}
function setMaxMintAmountPerTransaction(uint256 _newmaxMintAmount) public onlyOwner() {
setMaxMintAmountPerTxn = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function revertPause() external onlyOwner {
paused = !paused;
}
function withdraw() external payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
}
|
This function will be used for Main sale
|
function saleMint(uint256 _mintAmount) public payable {
if (msg.sender != owner()){
require(!paused, "Public sale is not live, can't mint");
require(_mintAmount <= setMaxMintAmountPerTxn, "Max Mint amount exceeded");
require(startMainSale == true, "Main sale is not started yet");
}
require(_mintAmount > 0, "Need to mint at least 1 FF");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded");
require(
_totalMintedMainsale[msg.sender] + _mintAmount <= maxMintAmountPerWallet,
"exceeded presale total mints per wallet"
);
if (msg.sender != owner()) {
if (_giftFreeMint[msg.sender]==false){
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
else{
require(_mintAmount == 1, "You can only 1 free mint");
_giftFreeMint[msg.sender]=false;
}
}
_safeMint(msg.sender, _mintAmount);
}
| 2,417,605
|
pragma solidity 0.4.18;
import "./Killable.sol";
import "./Product.sol";
import "./Order.sol";
contract Shop is Killable {
struct ProductStruct {
Product product;
uint index;
}
struct OrderStruct {
Order order;
uint index;
bool paid;
}
mapping (address => ProductStruct) public productsStruct;
address[] public productIndex;
mapping (address => OrderStruct) public ordersStruct;
address[] public orderIndex;
address public merchant;
uint public balance;
bytes32 public name;
event LogSetShopName(address indexed who, bytes32 indexed name);
event LogSetMerchant(address indexed who, address indexed merchant);
event LogAddProduct(address indexed who, address indexed product, bytes32 indexed name, bytes32 sku, bytes32 category, uint price, uint stock, bytes32 image);
event LogRemoveProduct(address indexed who, address indexed product, bytes32 indexed name, bytes32 sku, bytes32 category);
event LogSubmitOrder(address indexed who, address indexed order, uint indexed total);
modifier isOwnerOrMerchant() {
require(msg.sender == owner || msg.sender == merchant);
_;
}
modifier onlyIfProduct(address productAddress) {
require(productsStruct[productAddress].product != address(0));
_;
}
function Shop(address _merchant, bytes32 _name) Ownable() public {
require(_merchant != address(0));
require(_name != "");
merchant = _merchant;
name = _name;
}
function getProductCount()
public
constant
returns(uint productCount)
{
return productIndex.length;
}
function getOrderCount()
public
constant
returns(uint orderCount)
{
return orderIndex.length;
}
function setShopName(bytes32 _name)
isOwnerOrMerchant
public
returns(bool success)
{
require(_name != "");
require(_name != name);
name = _name;
LogSetShopName(msg.sender, _name);
return true;
}
function setMerchant(address _merchant)
isOwnerOrMerchant
public
returns(bool success)
{
require(_merchant != address(0));
require(_merchant != merchant);
merchant = _merchant;
LogSetMerchant(msg.sender, _merchant);
return true;
}
function addProduct(
bytes32 _name,
bytes32 _sku,
bytes32 _category,
uint _price,
uint _stock,
bytes32 _image
)
isOwnerOrMerchant
public
returns(address productContract)
{
require(_name != "");
require(_sku != "");
require(_category != "");
Product trustedProduct = new Product(merchant, _name, _sku, _category, _price, _stock, _image);
productIndex.push(trustedProduct);
productsStruct[trustedProduct].product = trustedProduct;
productsStruct[trustedProduct].index = productIndex.length - 1;
LogAddProduct(msg.sender, trustedProduct, _name, _sku, _category, _price, _stock, _image);
return trustedProduct;
}
function removeProduct(address _product)
isOwnerOrMerchant
onlyIfProduct(_product)
public
returns(bool success)
{
Product trustedProduct = Product(_product);
bytes32 productName = trustedProduct.name();
bytes32 productSku = trustedProduct.sku();
bytes32 productCategory = trustedProduct.category();
require(trustedProduct.destroy());
uint rowToDelete = productsStruct[_product].index;
address keyToMove = productIndex[productIndex.length-1];
productIndex[rowToDelete] = keyToMove;
productsStruct[keyToMove].index = rowToDelete;
productIndex.length = productIndex.length - 1;
LogRemoveProduct(msg.sender, _product, productName, productSku, productCategory);
return true;
}
function submitOrder(address _order)
public
payable
returns(bool success)
{
// validate order
Order untrustedOrder = Order(_order);
// Only 10 unique items - no unnounded looping
require(untrustedOrder.killed() != true);
require(untrustedOrder.paused() != true);
require(untrustedOrder.status() == Order.OrderStatus.Created);
require(untrustedOrder.total() > 0);
require(msg.value == untrustedOrder.total());
require(msg.value + balance > balance);
balance += msg.value;
uint productCount = untrustedOrder.getProductCount();
require(productCount > 0);
require(productCount < 10);
uint orderTotal = 0;
// accounting, in case we have been duped
for (uint8 i = 0; i < productCount; i++) {
Product untrustedProduct = Product(untrustedOrder.getProductAtIndex(i));
uint productQuantity = untrustedOrder.getProductQuantityAtIndex(i);
uint productStock = untrustedProduct.stock();
uint remainingStock = productStock - productQuantity;
require(productQuantity > 0);
require(productQuantity <= untrustedProduct.stock());
require(remainingStock < productStock);
uint productPrice = untrustedProduct.price();
uint productTotal = productPrice * productQuantity;
require(productTotal > 0);
require(productTotal >= productPrice);
require(orderTotal + productTotal > orderTotal);
require(untrustedProduct.setStock(remainingStock));
orderTotal += productTotal;
}
require(orderTotal == msg.value);
require(untrustedOrder.setStatus(Order.OrderStatus.Paid));
orderIndex.push(untrustedOrder);
ordersStruct[untrustedOrder].order = untrustedOrder;
ordersStruct[untrustedOrder].index = orderIndex.length;
LogSubmitOrder(msg.sender, _order, orderTotal);
return true;
}
}
|
validate order Only 10 unique items - no unnounded looping accounting, in case we have been duped
|
function submitOrder(address _order)
public
payable
returns(bool success)
{
Order untrustedOrder = Order(_order);
require(untrustedOrder.killed() != true);
require(untrustedOrder.paused() != true);
require(untrustedOrder.status() == Order.OrderStatus.Created);
require(untrustedOrder.total() > 0);
require(msg.value == untrustedOrder.total());
require(msg.value + balance > balance);
balance += msg.value;
uint productCount = untrustedOrder.getProductCount();
require(productCount > 0);
require(productCount < 10);
uint orderTotal = 0;
for (uint8 i = 0; i < productCount; i++) {
Product untrustedProduct = Product(untrustedOrder.getProductAtIndex(i));
uint productQuantity = untrustedOrder.getProductQuantityAtIndex(i);
uint productStock = untrustedProduct.stock();
uint remainingStock = productStock - productQuantity;
require(productQuantity > 0);
require(productQuantity <= untrustedProduct.stock());
require(remainingStock < productStock);
uint productPrice = untrustedProduct.price();
uint productTotal = productPrice * productQuantity;
require(productTotal > 0);
require(productTotal >= productPrice);
require(orderTotal + productTotal > orderTotal);
require(untrustedProduct.setStock(remainingStock));
orderTotal += productTotal;
}
require(orderTotal == msg.value);
require(untrustedOrder.setStatus(Order.OrderStatus.Paid));
orderIndex.push(untrustedOrder);
ordersStruct[untrustedOrder].order = untrustedOrder;
ordersStruct[untrustedOrder].index = orderIndex.length;
LogSubmitOrder(msg.sender, _order, orderTotal);
return true;
}
| 2,498,716
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
import "../IERC20.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 Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IFactory {
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IRouter {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
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 removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IWrapper {
struct WrapParams {
address sourceToken;
address [] destinationTokens;
address [] path1;
address [] path2;
uint256 amount;
uint256 [] userSlippageToleranceAmounts;
uint256 deadline;
}
struct UnwrapParams {
address lpTokenPairAddress;
address destinationToken;
address [] path1;
address [] path2;
uint256 amount;
uint256 [] userSlippageToleranceAmounts;
uint256 [] minUnwrapAmounts;
uint256 deadline;
}
struct RemixWrapParams {
address [] sourceTokens;
address [] destinationTokens;
address [] path1;
address [] path2;
uint256 amount1;
uint256 amount2;
uint256 [] userSlippageToleranceAmounts;
uint256 deadline;
}
struct RemixParams {
address lpTokenPairAddress;
address [] destinationTokens;
address [] wrapPath1;
address [] wrapPath2;
uint256 amount;
uint256 [] remixWrapSlippageToleranceAmounts;
uint256 [] minUnwrapAmounts;
uint256 deadline;
bool crossDexRemix;
}
function wrap(WrapParams memory params)
external
payable
returns (address, uint256);
function unwrap(UnwrapParams memory params)
external
payable
returns (uint256);
function remix(RemixParams memory params)
external
payable
returns (address, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface ILPERC20 {
function token0() external view returns (address);
function token1() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/token/IWETH.sol";
import "../interfaces/token/ILPERC20.sol";
import "../interfaces/IWrapper.sol";
import "../interfaces/IRouter.sol";
import "../interfaces/IFactory.sol";
/// @title Plexus LP Wrapper Contract
/// @author Team Plexus
contract WrapAndUnWrap is IWrapper {
using SafeERC20 for IERC20;
// Contract state variables
bool public changeRecipientIsOwner;
address public WETH_TOKEN_ADDRESS; // Contract address for WETH tokens
address public uniAddress;
address public sushiAddress;
address public uniFactoryAddress;
address public sushiFactoryAddress;
address public owner;
uint256 public fee;
uint256 public maxfee;
IRouter public uniswapExchange;
IFactory public factory;
// events
event WrapV2(address lpTokenPairAddress, uint256 amount);
event UnWrapV2(uint256 amount);
event LpTokenRemixWrap(address lpTokenPairAddress, uint256 amount);
constructor(
address _weth,
address _uniAddress,
address _sushiAddress,
address _uniFactoryAddress,
address _sushiFactoryAddress
)
payable
{
// init the addresses
WETH_TOKEN_ADDRESS = _weth;
uniAddress = _uniAddress;
sushiAddress = _sushiAddress;
uniFactoryAddress = _uniFactoryAddress;
sushiFactoryAddress = _sushiFactoryAddress;
// init the router and factories
uniswapExchange = IRouter(uniAddress);
factory = IFactory(uniFactoryAddress);
// init the fees params
fee = 0;
maxfee = 0;
changeRecipientIsOwner = false;
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "Not contract owner!");
_;
}
/**
* @notice Executed on a call to the contract if none of the other
* functions match the given function signature, or if no data was
* supplied at all and there is no receive Ether function
*/
fallback() external payable {
}
/**
* @notice Function executed on plain ether transfers and on a call to the
* contract with empty calldata
*/
receive() external payable {
}
/**
* @notice Allow owner to collect a small fee from trade imbalances on
* LP conversions
* @param changeRecipientIsOwnerBool If set to true, allows owner to collect
* fees from pair imbalances
*/
function updateChangeRecipientBool(
bool changeRecipientIsOwnerBool
)
external
onlyOwner
returns (bool)
{
changeRecipientIsOwner = changeRecipientIsOwnerBool;
return true;
}
/**
* @notice Update the Uniswap exchange contract address
* @param newAddress Uniswap exchange contract address to be updated
*/
function updateUniswapExchange(address newAddress) external onlyOwner returns (bool) {
uniswapExchange = IRouter(newAddress);
uniAddress = newAddress;
return true;
}
/**
* @notice Update the Uniswap factory contract address
* @param newAddress Uniswap factory contract address to be updated
*/
function updateUniswapFactory(address newAddress) external onlyOwner returns (bool) {
factory = IFactory(newAddress);
uniFactoryAddress = newAddress;
return true;
}
/**
* @notice Allow admins to withdraw accidentally deposited tokens
* @param token Address to the token to be withdrawn
* @param amount Amount of specified token to be withdrawn
* @param destination Address where the withdrawn tokens should be
* transferred
*/
function adminEmergencyWithdrawTokens(
address token,
uint256 amount,
address payable destination
)
public
onlyOwner
returns (bool)
{
if (address(token) == address(0x0)) {
destination.transfer(amount);
} else {
IERC20 token_ = IERC20(token);
token_.safeTransfer(destination, amount);
}
return true;
}
/**
* @notice Update the protocol fee rate
* @param newFee Updated fee rate to be charged
*/
function setFee(uint256 newFee) public onlyOwner returns (bool) {
require(
newFee <= maxfee,
"Admin cannot set the fee higher than the current maxfee"
);
fee = newFee;
return true;
}
/**
* @notice Set the max protocol fee rate
* @param newMax Updated maximum fee rate value
*/
function setMaxFee(uint256 newMax) public onlyOwner returns (bool) {
require(maxfee == 0, "Admin can only set max fee once and it is perm");
maxfee = newMax;
return true;
}
function swap(
address sourceToken,
address destinationToken,
address[] memory path,
uint256 amount,
uint256 userSlippageToleranceAmount,
uint256 deadline
) private returns (uint256) {
if (sourceToken != address(0x0)) {
IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), amount);
}
conductUniswap(sourceToken, destinationToken, path, amount, userSlippageToleranceAmount, deadline);
uint256 thisBalance = IERC20(destinationToken).balanceOf(address(this));
IERC20(destinationToken).safeTransfer(msg.sender, thisBalance);
return thisBalance;
}
function chargeFees(address token1, address token2) private {
address thisPairAddress = factory.getPair(token1, token2);
// if we get a zero address for the pair address, then we we assume,
// we're using the wrong factory and so we switch to the sushi one
if (thisPairAddress == address(0)) {
IFactory fct = IFactory(sushiFactoryAddress);
thisPairAddress = fct.getPair(token1, token2);
}
IERC20 lpToken = IERC20(thisPairAddress);
uint256 thisBalance = lpToken.balanceOf(address(this));
IERC20 dToken1 = IERC20(token1);
IERC20 dToken2 = IERC20(token2);
if (fee > 0) {
uint256 totalFee = (thisBalance * fee) / 10000;
if (totalFee > 0) {
lpToken.safeTransfer(owner, totalFee);
}
thisBalance = lpToken.balanceOf(address(this));
lpToken.safeTransfer(msg.sender, thisBalance);
} else {
lpToken.safeTransfer(msg.sender, thisBalance);
}
// Transfer any change to changeRecipient
// (from a pair imbalance. Should never be more than a few basis points)
address changeRecipient = msg.sender;
if (changeRecipientIsOwner == true) {
changeRecipient = owner;
}
if (dToken1.balanceOf(address(this)) > 0) {
dToken1.safeTransfer(changeRecipient, dToken1.balanceOf(address(this)));
}
if (dToken2.balanceOf(address(this)) > 0) {
dToken2.safeTransfer(changeRecipient, dToken2.balanceOf(address(this)));
}
}
function createRemixWrap(RemixWrapParams memory params, bool crossDexRemix) private returns (address, uint256) {
IRouter router = uniswapExchange;
IFactory fct = factory;
// for a cross-dex remix we init both the router and the factory to the sushi router and factory addresses respectively
if(crossDexRemix) {
router = IRouter(sushiAddress);
fct = IFactory(sushiFactoryAddress);
}
if (params.sourceTokens[0] != params.destinationTokens[0]) {
conductSwapT4TRemix(
router,
params.path1,
params.amount1,
params.userSlippageToleranceAmounts[0],
params.deadline
);
}
if (params.sourceTokens[1] != params.destinationTokens[1]) {
conductSwapT4TRemix(
router,
params.path2,
params.amount2,
params.userSlippageToleranceAmounts[1],
params.deadline
);
}
// then finally add liquidity to that pool in the respective dex
IERC20 dToken1 = IERC20(params.destinationTokens[0]);
IERC20 dToken2 = IERC20(params.destinationTokens[1]);
uint256 dTokenBalance1 = dToken1.balanceOf(address(this));
uint256 dTokenBalance2 = dToken2.balanceOf(address(this));
if (crossDexRemix) {
if (dToken1.allowance(address(this), sushiAddress) < dTokenBalance1 * 2) {
dToken1.safeIncreaseAllowance(sushiAddress, dTokenBalance1 * 3);
}
if (dToken2.allowance(address(this), sushiAddress) < dTokenBalance2 * 2) {
dToken2.safeIncreaseAllowance(sushiAddress, dTokenBalance2 * 3);
}
} else {
if (dToken1.allowance(address(this), uniAddress) < dTokenBalance1 * 2) {
dToken1.safeIncreaseAllowance(uniAddress, dTokenBalance1 * 3);
}
if (dToken2.allowance(address(this), uniAddress) < dTokenBalance2 * 2) {
dToken2.safeIncreaseAllowance(uniAddress, dTokenBalance2 * 3);
}
}
// we add the remixed liquidity here
router.addLiquidity(
params.destinationTokens[0],
params.destinationTokens[1],
dTokenBalance1,
dTokenBalance2,
1,
1,
address(this),
1000000000000000000000000000
);
address thisPairAddress = fct.getPair(params.destinationTokens[0], params.destinationTokens[1]);
IERC20 lpToken = IERC20(thisPairAddress);
uint256 thisBalance = lpToken.balanceOf(address(this));
// charge the necesssary fees if available and also transfer change
chargeFees(params.destinationTokens[0], params.destinationTokens[1]);
return (thisPairAddress, thisBalance);
}
function createWrap(WrapParams memory params) private returns (address, uint256) {
uint256 amount = params.amount;
if (params.sourceToken == address(0x0)) {
IWETH(WETH_TOKEN_ADDRESS).deposit{value: msg.value}();
amount = msg.value;
} else {
IERC20(params.sourceToken).safeTransferFrom(msg.sender, address(this), amount);
}
if (params.destinationTokens[0] == address(0x0)) {
params.destinationTokens[0] = WETH_TOKEN_ADDRESS;
}
if (params.destinationTokens[1] == address(0x0)) {
params.destinationTokens[1] = WETH_TOKEN_ADDRESS;
}
if (params.sourceToken != params.destinationTokens[0]) {
conductUniswap(
params.sourceToken,
params.destinationTokens[0],
params.path1,
(amount / 2),
params.userSlippageToleranceAmounts[0],
params.deadline
);
}
if (params.sourceToken != params.destinationTokens[1]) {
conductUniswap(
params.sourceToken,
params.destinationTokens[1],
params.path2,
(amount / 2),
params.userSlippageToleranceAmounts[1],
params.deadline
);
}
IERC20 dToken1 = IERC20(params.destinationTokens[0]);
IERC20 dToken2 = IERC20(params.destinationTokens[1]);
uint256 dTokenBalance1 = dToken1.balanceOf(address(this));
uint256 dTokenBalance2 = dToken2.balanceOf(address(this));
if (dToken1.allowance(address(this), uniAddress) < dTokenBalance1 * 2) {
dToken1.safeIncreaseAllowance(uniAddress, dTokenBalance1 * 3);
}
if (dToken2.allowance(address(this), uniAddress) < dTokenBalance2 * 2) {
dToken2.safeIncreaseAllowance(uniAddress, dTokenBalance2 * 3);
}
uniswapExchange.addLiquidity(
params.destinationTokens[0],
params.destinationTokens[1],
dTokenBalance1,
dTokenBalance2,
1,
1,
address(this),
1000000000000000000000000000
);
address thisPairAddress = factory.getPair(params.destinationTokens[0], params.destinationTokens[1]);
IERC20 lpToken = IERC20(thisPairAddress);
uint256 thisBalance = lpToken.balanceOf(address(this));
// charge the necesssary fees if available and also transfer change
chargeFees(params.destinationTokens[0], params.destinationTokens[1]);
return (thisPairAddress, thisBalance);
}
/**
* @notice Wrap a source token based on the specified
* @param params params of struct WrapParams
* // contains following properties
// sourceToken Address to the source token contract
// destinationTokens Array describing the token(s) which the source
// paths Paths for uniswap
// amount Amount of source token to be wrapped
// userSlippageTolerance Maximum permissible user slippage tolerance
* @return Address to the token contract for the destination token and the
* amount of wrapped tokens
*/
function wrap(
WrapParams memory params
)
override
external
payable
returns (address, uint256)
{
if (params.destinationTokens.length == 1) {
uint256 swapAmount = swap(params.sourceToken, params.destinationTokens[0], params.path1, params.amount, params.userSlippageToleranceAmounts[0], params.deadline);
return (params.destinationTokens[0], swapAmount);
} else {
(address lpTokenPairAddress, uint256 lpTokenAmount) = createWrap(params);
emit WrapV2(lpTokenPairAddress, lpTokenAmount);
return (lpTokenPairAddress, lpTokenAmount);
}
}
// the function that does the actual liquidity removal
function removePoolLiquidity(
address lpTokenAddress,
uint256 amount,
uint256 minUnwrapAmount1,
uint256 minUnwrapAmount2,
uint256 deadline
)
private returns (uint256, uint256){
ILPERC20 lpTokenInfo = ILPERC20(lpTokenAddress);
address token0 = lpTokenInfo.token0();
address token1 = lpTokenInfo.token1();
uniswapExchange.removeLiquidity(
token0,
token1,
amount,
minUnwrapAmount1,
minUnwrapAmount2,
address(this),
deadline
);
uint256 pTokenBalance = IERC20(token0).balanceOf(address(this));
uint256 pTokenBalance2 = IERC20(token1).balanceOf(address(this));
return (pTokenBalance, pTokenBalance2);
}
// Function that does the actual unwrapping and converts the 2 pool tokens to the output token
function removeWrap(UnwrapParams memory params) private returns (uint256){
address originalDestinationToken = params.destinationToken;
IERC20 sToken = IERC20(params.lpTokenPairAddress);
if (params.destinationToken == address(0x0)) {
params.destinationToken = WETH_TOKEN_ADDRESS;
}
if (params.lpTokenPairAddress != address(0x0)) {
sToken.safeTransferFrom(msg.sender, address(this), params.amount);
}
ILPERC20 thisLpInfo = ILPERC20(params.lpTokenPairAddress);
address token0 = thisLpInfo.token0();
address token1 = thisLpInfo.token1();
if (sToken.allowance(address(this), uniAddress) < params.amount * 2) {
sToken.safeIncreaseAllowance(uniAddress, params.amount * 3);
}
// unwrap the LP token to get the constituent tokens
( uint256 pTokenBalance, uint256 pTokenBalance2 )= removePoolLiquidity(
params.lpTokenPairAddress,
params.amount,
params.minUnwrapAmounts[0],
params.minUnwrapAmounts[1],
params.deadline
);
if (token0 != params.destinationToken) {
conductUniswap(
token0,
params.destinationToken,
params.path1,
pTokenBalance,
params.userSlippageToleranceAmounts[0],
params.deadline
);
}
if (token1 != params.destinationToken) {
conductUniswap(
token1,
params.destinationToken,
params.path2,
pTokenBalance2,
params.userSlippageToleranceAmounts[1],
params.deadline
);
}
IERC20 dToken = IERC20(params.destinationToken);
uint256 destinationTokenBalance = dToken.balanceOf(address(this));
if (originalDestinationToken == address(0x0)) {
IWETH(WETH_TOKEN_ADDRESS).withdraw(destinationTokenBalance);
if (fee > 0) {
uint256 totalFee = (address(this).balance * fee) / 10000;
if (totalFee > 0) {
payable(owner).transfer(totalFee);
}
payable(msg.sender).transfer(address(this).balance);
} else {
payable(msg.sender).transfer(address(this).balance);
}
} else {
if (fee > 0) {
uint256 totalFee = (destinationTokenBalance * fee) / 10000;
if (totalFee > 0) {
dToken.safeTransfer(owner, totalFee);
}
destinationTokenBalance = dToken.balanceOf(address(this));
dToken.safeTransfer(msg.sender, destinationTokenBalance);
} else {
dToken.safeTransfer(msg.sender, destinationTokenBalance);
}
}
emit UnWrapV2(destinationTokenBalance);
return destinationTokenBalance;
}
/**
* @notice Unwrap a source token based to the specified destination token
* @param params params of struct UnwrapParams
it contains following properties
// param lpTokenPairAddress address for lp token
// destinationToken Address of the destination token contract
// paths Paths for uniswap
// amount Amount of source token to be unwrapped
// userSlippageToleranceAmounts Maximum permissible user slippage tolerance
* @return Amount of the destination token returned from unwrapping the
* source token
*/
function unwrap(
UnwrapParams memory params
)
override
public
payable
returns (uint256)
{
uint256 destAmount = removeWrap(params);
return destAmount;
}
/**
* @notice Unwrap a source token and wrap it into a different destination token
* @param params Remix params having following properties
// lpTokenPairAddress Address for the LP pair to remix
// unwrapOutputToken Address for the initial output token of remix
// destinationTokens Address to the destination tokens to be remixed to
// unwrapPaths Paths best uniswap trade paths for doing the unwrapping
// wrapPaths Paths best uniswap trade paths for doing the wrapping to the new LP token
// amount Amount of LP Token to be remixed
// userSlippageToleranceAmounts Maximum permissible user slippage tolerance
// deadline Timeout after which the txn should revert
// crossDexRemix Indicates whether this is a cross-dex remix or not
* @return Address of the LP token returned from unwrapping the source LP token
* @return Amount of the LP token returned from unwrapping the source LP token
*/
function remix(RemixParams memory params)
override
public
payable
returns (address, uint256)
{
uint lpTokenAmount = 0;
address lpTokenAddress = address(0);
// first of all we remove liquidity from the pool
IERC20 lpToken = IERC20(params.lpTokenPairAddress);
if (params.lpTokenPairAddress != address(0x0)) {
lpToken.safeTransferFrom(msg.sender, address(this), params.amount);
}
if (lpToken.allowance(address(this), uniAddress) < params.amount * 2) {
lpToken.safeIncreaseAllowance(uniAddress, params.amount * 3);
}
if (lpToken.allowance(address(this), sushiAddress) < params.amount * 2) {
lpToken.safeIncreaseAllowance(sushiAddress, params.amount * 3);
}
ILPERC20 lpTokenInfo = ILPERC20(params.lpTokenPairAddress);
address token0 = lpTokenInfo.token0();
address token1 = lpTokenInfo.token1();
// the actual liquidity removal from the pool
(uint256 pTokenBalance1, uint256 pTokenBalance2) = removePoolLiquidity(
params.lpTokenPairAddress,
params.amount,
params.minUnwrapAmounts[0],
params.minUnwrapAmounts[1],
params.deadline
);
// if pool liquidity removal is successful, then proceed with the remix wrap
if (pTokenBalance1 > 0 && pTokenBalance2 > 0) {
address[] memory sTokens = new address[](2);
sTokens[0] = token0;
sTokens[1] = token1;
if (params.crossDexRemix) {
IERC20 sToken0 = IERC20(sTokens[0]);
if (sToken0.allowance(address(this), sushiAddress) < pTokenBalance1 * 2) {
sToken0.safeIncreaseAllowance(sushiAddress, pTokenBalance1 * 3);
}
IERC20 sToken1 = IERC20(sTokens[1]);
if (sToken1.allowance(address(this), sushiAddress) < pTokenBalance2 * 2) {
sToken1.safeIncreaseAllowance(sushiAddress, pTokenBalance2 * 3);
}
} else {
IERC20 sToken0 = IERC20(sTokens[0]);
if (sToken0.allowance(address(this), uniAddress) < pTokenBalance1 * 2) {
sToken0.safeIncreaseAllowance(uniAddress, pTokenBalance1 * 3);
}
IERC20 sToken1 = IERC20(sTokens[1]);
if (sToken1.allowance(address(this), uniAddress) < pTokenBalance2 * 2) {
sToken1.safeIncreaseAllowance(uniAddress, pTokenBalance2 * 3);
}
}
// then now we create the new LP token
RemixWrapParams memory remixParams = RemixWrapParams({
sourceTokens: sTokens,
destinationTokens: params.destinationTokens,
path1: params.wrapPath1,
path2: params.wrapPath2,
amount1: pTokenBalance1,
amount2: pTokenBalance2,
userSlippageToleranceAmounts: params.remixWrapSlippageToleranceAmounts,
deadline: params.deadline
});
// do the actual remix
(lpTokenAddress, lpTokenAmount) = createRemixWrap(remixParams, params.crossDexRemix);
emit LpTokenRemixWrap(lpTokenAddress, lpTokenAmount);
}
return (lpTokenAddress, lpTokenAmount);
}
/**
* @notice Given an input asset amount and an array of token addresses,
* calculates all subsequent maximum output token amounts for each pair of
* token addresses in the path.
* @param theAddresses Array of addresses that form the Routing swap path
* @param amount Amount of input asset token
* @return amounts1 Array with maximum output token amounts for all token
* pairs in the swap path
*/
function getAmountsOut(address[] memory theAddresses, uint256 amount)
public
view
returns (uint256[] memory amounts1) {
try uniswapExchange.getAmountsOut(
amount,
theAddresses
) returns (uint256[] memory amounts) {
return amounts;
} catch {
uint256[] memory amounts2 = new uint256[](2);
amounts2[0] = 0;
amounts2[1] = 0;
return amounts2;
}
}
/**
* @notice Retrieve the LP token address for a given pair of tokens
* @param token1 Address to the first token in the LP pair
* @param token2 Address to the second token in the LP pair
* @return lpAddr Address to the LP token contract composed of the given token pair
*/
function getLPTokenByPair(
address token1,
address token2
)
public
view
returns (address lpAddr)
{
address thisPairAddress = factory.getPair(token1, token2);
return thisPairAddress;
}
/**
* @notice Retrieve the details of the constituent tokens in an LP Token/Pair
* @param lpTokenAddress Address to the LP token
* @return token0Name Name of token 0
* @return token0Symbol Symbol of token 0
* @return token0Decimals Decimal of token 0
* @return token1Name Namme of token 1
* @return token1Symbol Symbol of token 1
* @return token1Decimals Symbol of token 1
*/
function getPoolTokensDetails(address lpTokenAddress)
external
view
returns (string memory token0Name, string memory token0Symbol, uint256 token0Decimals,
string memory token1Name, string memory token1Symbol, uint256 token1Decimals)
{
// get the pool token addresses
address token0 = ILPERC20(lpTokenAddress).token0();
address token1 = ILPERC20(lpTokenAddress).token1();
// Then get the pool token details
string memory t0Name = ERC20(token0).name();
string memory t0Symbol = ERC20(token0).symbol();
uint256 t0Decimals = ERC20(token0).decimals();
string memory t1Name = ERC20(token0).name();
string memory t1Symbol = ERC20(token1).symbol();
uint256 t1Decimals = ERC20(token1).decimals();
return (t0Name, t0Symbol, t0Decimals, t1Name, t1Symbol, t1Decimals);
}
/**
* @notice Retrieve the balance of a given token for a specified user
* @param userAddress Address to the user's wallet
* @param tokenAddress Address to the token for which the balance is to be
* retrieved
* @return Balance of the given token in the specified user wallet
*/
function getUserTokenBalance(
address userAddress,
address tokenAddress
)
public
view
returns (uint256)
{
IERC20 token = IERC20(tokenAddress);
return token.balanceOf(userAddress);
}
/**
* @notice Perform a Uniswap transaction to swap between a given pair of
* tokens of the specified amount
* @param sellToken Address to the token being sold as part of the swap
* @param buyToken Address to the token being bought as part of the swap
* @param path Path for uniswap
* @param amount Transaction amount denoted in terms of the token sold
* @param userSlippageToleranceAmount Maximum permissible slippage limit
* @return amounts1 Tokens received once the swap is completed
*/
function conductUniswap(
address sellToken,
address buyToken,
address[] memory path,
uint256 amount,
uint256 userSlippageToleranceAmount,
uint256 deadline
)
internal
returns (uint256 amounts1)
{
if (sellToken == address(0x0) && buyToken == WETH_TOKEN_ADDRESS) {
IWETH(buyToken).deposit{value: msg.value}();
return amount;
}
if (sellToken == address(0x0)) {
// addresses[0] = WETH_TOKEN_ADDRESS;
// addresses[1] = buyToken;
uniswapExchange.swapExactETHForTokens{value: msg.value}(
userSlippageToleranceAmount,
path,
address(this),
deadline
);
} else {
IERC20 sToken = IERC20(sellToken);
if (sToken.allowance(address(this), uniAddress) < amount * 2) {
sToken.safeIncreaseAllowance(uniAddress, amount * 3);
}
uint256[] memory amounts = conductUniswapT4T(
path,
amount,
userSlippageToleranceAmount,
deadline
);
uint256 resultingTokens = amounts[amounts.length - 1];
return resultingTokens;
}
}
/**
* @notice Using Uniswap, exchange an exact amount of input tokens for as
* many output tokens as possible, along the route determined by the path.
* @param paths Array of addresses representing the path where the
* first address is the input token and the last address is the output
* token
* @param amount Amount of input tokens to be swapped
* @param userSlippageToleranceAmount Maximum permissible slippage tolerance
* @return amounts_ The input token amount and all subsequent output token
* amounts
*/
function conductUniswapT4T(
address[] memory paths,
uint256 amount,
uint256 userSlippageToleranceAmount,
uint256 deadline
)
internal
returns (uint256[] memory amounts_)
{
uint256[] memory amounts =
uniswapExchange.swapExactTokensForTokens(
amount,
userSlippageToleranceAmount,
paths,
address(this),
deadline
);
return amounts;
}
/**
* @notice Using either Uniswap or Sushiswap, exchange an exact amount of input tokens for as
* many output tokens as possible, along the route determined by the path.
* @param path Array of addresses representing the path where the
* first address is the input token and the last address is the output
* token
* @param amount Amount of input tokens to be swapped
* @param userSlippageToleranceAmount Maximum permissible slippage tolerance
* @return amounts_ The input token amount and all subsequent output token
* amounts
*/
function conductSwapT4TRemix(
IRouter router,
address[] memory path,
uint256 amount,
uint256 userSlippageToleranceAmount,
uint256 deadline
)
internal
returns (uint256[] memory amounts_)
{
uint256[] memory amounts =
router.swapExactTokensForTokens(
amount,
userSlippageToleranceAmount,
path,
address(this),
deadline
);
return amounts;
}
}
|
Wrap a source token based on the specified params params of struct WrapParams sourceToken Address to the source token contract destinationTokens Array describing the token(s) which the source paths Paths for uniswap amount Amount of source token to be wrapped userSlippageTolerance Maximum permissible user slippage tolerance return Address to the token contract for the destination token and the amount of wrapped tokens/
|
function wrap(
WrapParams memory params
)
override
external
payable
returns (address, uint256)
{
if (params.destinationTokens.length == 1) {
uint256 swapAmount = swap(params.sourceToken, params.destinationTokens[0], params.path1, params.amount, params.userSlippageToleranceAmounts[0], params.deadline);
return (params.destinationTokens[0], swapAmount);
(address lpTokenPairAddress, uint256 lpTokenAmount) = createWrap(params);
emit WrapV2(lpTokenPairAddress, lpTokenAmount);
return (lpTokenPairAddress, lpTokenAmount);
}
}
| 11,814,954
|
// SPDX-License-Identifier: GPL-3.0
/*//////////////////////////////////////////////////////////////////////////////////////////////////
*
* _____ ____ __ __ __ __ _ _ _____ ______ _____ _____ ______ ______ _____
* / ____/ __ \| \/ | \/ | /\ | \ | | __ \| ____| __ \ | __ \| ____| ____|_ _|
* | | | | | | \ / | \ / | / \ | \| | | | | |__ | |__) | | | | | |__ | |__ | |
* | | | | | | |\/| | |\/| | / /\ \ | . ` | | | | __| | _ / | | | | __| | __| | |
* | |___| |__| | | | | | | |/ ____ \| |\ | |__| | |____| | \ \ | |__| | |____| | _| |_
* \_____\____/|_| |_|_| |_/_/ \_\_| \_|_____/|______|_| \_\ |_____/|______|_| |_____|
*
* Dedicated to the rugged MSMI community, reborn into the hands of the Commander. XOXO. King.
*//////////////////////////////////////////////////////////////////////////////////////////////////
pragma solidity ^0.8.3;
import 'Ownable.sol';
import 'SafeMath.sol';
import 'Address.sol';
import 'IERC20.sol';
contract CommanderDefi is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => uint256) public totalTokensTransferred;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
struct ValuesResult {
uint256 tTransferAmount;
uint256 tFee;
uint256 tLiquidity;
uint256 tCommunity;
uint256 tMaintenance;
uint256 tLiquidityWallet;
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 rLiquidity;
uint256 rCommunity;
uint256 rMaintenance;
uint256 rLiquidityWallet;
}
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100**7 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Commander DeFi";
string private constant _symbol = "COMFI";
uint8 private constant _decimals = 18;
// fees
uint256 public _taxFee = 100;
uint256 private _previousTaxFee = _taxFee;
uint256 public _communityFee = 300;
uint256 private _previousCommunityFee = _communityFee;
uint256 public _maintenanceFee = 300;
uint256 private _previousMaintenanceFee = _maintenanceFee;
uint256 public _liquidityWalletFee = 300;
uint256 private _previousliquidityWalletFee = _liquidityWalletFee;
uint256 public _maxTxAmount = 540 * 10**3 * 10**18; // 0.005
event TaxFeePercentChanged(uint256 oldValue, uint256 newValue);
event CommunityFeePercentChanged(uint256 oldValue, uint256 newValue);
event MaintenanceFeePercentChanged(uint256 oldValue, uint256 newValue);
event LiquidityWalletFeePercentChanged(uint256 oldValue, uint256 newValue);
event MaxTxPermillChanged(uint256 oldValue, uint256 newValue);
constructor (address payable communityAddress, address payable maintenanceAddress, address payable liquidityWalletAddress) {
_rOwned[owner()] = _rTotal;
// exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
setCommunityAddress(communityAddress);
setMaintenanceAddress(maintenanceAddress);
setLiquidityWalletAddress(liquidityWalletAddress);
emit Transfer(address(0), owner(), _tTotal);
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimals;
}
function totalSupply() external pure override returns (uint256) {
return _tTotal;
}
function totalRSupply() external view onlyOwner() returns (uint256) {
return _rTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function balanceOfT(address account) external view onlyOwner() returns (uint256) {
return _tOwned[account];
}
function balanceOfR(address account) external view onlyOwner() returns (uint256) {
return _rOwned[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferOwnership(address newOwner) external virtual onlyOwner() {
emit OwnershipTransferred(owner(), newOwner);
_transfer(owner(), newOwner, balanceOf(owner()));
updateOwner(newOwner);
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcluded[account];
}
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public override onlyOwner(){
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public override onlyOwner{
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner(){
require(taxFee <= 100, "Cannot set percentage over 1.0%");
emit TaxFeePercentChanged(_taxFee, taxFee);
_taxFee = taxFee;
}
function setCommunityFeePercent(uint256 communityFee) external onlyOwner(){
require(communityFee <= 300, "Cannot set percentage over 3.00%");
emit CommunityFeePercentChanged(_communityFee, communityFee);
_communityFee = communityFee;
}
function setMaintenanceFeePercent(uint256 maintenanceFee) external onlyOwner(){
require(maintenanceFee <= 300, "Cannot set percentage over 3.0%");
emit MaintenanceFeePercentChanged(_maintenanceFee, maintenanceFee);
_maintenanceFee = maintenanceFee;
}
function setLiquidityWalletFeePercent(uint256 liquidityWalletFee) external onlyOwner(){
require(liquidityWalletFee <= 300, "Cannot set percentage over 3.0%");
emit LiquidityWalletFeePercentChanged(_liquidityWalletFee, liquidityWalletFee);
_liquidityWalletFee = liquidityWalletFee;
}
function setMaxTxPermill(uint256 maxTxPermill) external onlyOwner(){
emit LiquidityWalletFeePercentChanged(_maxTxAmount, _tTotal.mul(maxTxPermill).div(10**3));
_maxTxAmount = _tTotal.mul(maxTxPermill).div(
10**3
);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
ValuesResult memory valuesResult = ValuesResult(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
_getTValues(tAmount, valuesResult);
_getRValues(tAmount, valuesResult, _getRate());
return (valuesResult.rAmount, valuesResult.rTransferAmount, valuesResult.rFee, valuesResult.tTransferAmount, valuesResult.tFee, valuesResult.tLiquidity, valuesResult.tCommunity, valuesResult.tMaintenance, valuesResult.tLiquidityWallet);
}
function _getTValues(uint256 tAmount, ValuesResult memory valuesResult) private view returns (ValuesResult memory) {
{
uint256 tFee = calculateTaxFee(tAmount);
valuesResult.tFee = tFee;
}
{
uint256 tCommunity = calculateCommunityFee(tAmount);
valuesResult.tCommunity = tCommunity;
}
{
uint256 tMaintenance = calculateMaintenanceFee(tAmount);
valuesResult.tMaintenance = tMaintenance;
}
{
uint256 tLiquidityWallet = calculateLiquidityWalletFee(tAmount);
valuesResult.tLiquidityWallet = tLiquidityWallet;
}
valuesResult.tTransferAmount = tAmount.sub(valuesResult.tFee).sub(valuesResult.tCommunity).sub(valuesResult.tMaintenance).sub(valuesResult.tLiquidityWallet);
return valuesResult;
}
function _getRValues(uint256 tAmount, ValuesResult memory valuesResult, uint256 currentRate) private pure returns (ValuesResult memory) {
{
uint256 rAmount = tAmount.mul(currentRate);
valuesResult.rAmount = rAmount;
}
{
uint256 rFee = valuesResult.tFee.mul(currentRate);
valuesResult.rFee = rFee;
}
{
uint256 rCommunity = valuesResult.tCommunity.mul(currentRate);
valuesResult.rCommunity = rCommunity;
}
{
uint256 rMaintenance = valuesResult.tMaintenance.mul(currentRate);
valuesResult.rMaintenance = rMaintenance;
}
{
uint256 rLiquidityWallet = valuesResult.tLiquidityWallet.mul(currentRate);
valuesResult.rLiquidityWallet = rLiquidityWallet;
}
valuesResult.rTransferAmount = valuesResult.rAmount.sub(valuesResult.rFee).sub(valuesResult.rCommunity).sub(valuesResult.rMaintenance).sub(valuesResult.rLiquidityWallet);
return (valuesResult);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function _takeCommunity(uint256 tCommunity) private {
uint256 currentRate = _getRate();
uint256 rCommunity = tCommunity.mul(currentRate);
_rOwned[community()] = _rOwned[community()].add(rCommunity);
if(_isExcluded[community()])
_tOwned[community()] = _tOwned[community()].add(tCommunity);
}
function _takeMaintenance(uint256 tMaintenance) private {
uint256 currentRate = _getRate();
uint256 rMaintenance = tMaintenance.mul(currentRate);
_rOwned[maintenance()] = _rOwned[maintenance()].add(rMaintenance);
if(_isExcluded[maintenance()])
_tOwned[maintenance()] = _tOwned[maintenance()].add(tMaintenance);
}
function _takeLiquidityWallet(uint256 tLiquidityWallet) private {
uint256 currentRate = _getRate();
uint256 rLiquidityWallet = tLiquidityWallet.mul(currentRate);
_rOwned[liquidityWallet()] = _rOwned[liquidityWallet()].add(rLiquidityWallet);
if(_isExcluded[liquidityWallet()])
_tOwned[liquidityWallet()] = _tOwned[liquidityWallet()].add(tLiquidityWallet);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**4
);
}
function calculateCommunityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_communityFee).div(
10**4
);
}
function calculateMaintenanceFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_maintenanceFee).div(
10**4
);
}
function calculateLiquidityWalletFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityWalletFee).div(
10**4
);
}
function removeAllFee() private {
if(_taxFee == 0) return;
_previousTaxFee = _taxFee;
_previousCommunityFee = _communityFee;
_previousMaintenanceFee = _maintenanceFee;
_previousliquidityWalletFee = _liquidityWalletFee;
_taxFee = 0;
_communityFee = 0;
_maintenanceFee = 0;
_liquidityWalletFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_communityFee = _previousCommunityFee;
_maintenanceFee = _previousMaintenanceFee;
_liquidityWalletFee = _previousliquidityWalletFee;
}
function isExcludedFromFee(address account) external view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function addTokensTransferred(address wallet, uint256 amount) private {
uint256 rate = _taxFee.add(_communityFee).add(_maintenanceFee).add(_liquidityWalletFee);
totalTokensTransferred[wallet] = totalTokensTransferred[wallet].add(amount.mul(rate).div(10**4));
}
function getTotalTokensTransferredHistory(address wallet) external view returns(uint256 amount){
amount = totalTokensTransferred[wallet];
return amount;
}
/**
* TRANSFER
*/
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
// if fees are calculated, then these amounts will be tracked in totalTokensTransferred[sender]
if(takeFee){
addTokensTransferred(from, amount);
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tCommunity, uint256 tMaintenance, uint256 tLiquidityWallet) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeCommunity(tCommunity);
_takeMaintenance(tMaintenance);
_takeLiquidityWallet(tLiquidityWallet);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tCommunity, uint256 tMaintenance, uint256 tLiquidityWallet) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeCommunity(tCommunity);
_takeMaintenance(tMaintenance);
_takeLiquidityWallet(tLiquidityWallet);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tCommunity, uint256 tMaintenance, uint256 tLiquidityWallet) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeCommunity(tCommunity);
_takeMaintenance(tMaintenance);
_takeLiquidityWallet(tLiquidityWallet);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tCommunity, uint256 tMaintenance, uint256 tLiquidityWallet) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeCommunity(tCommunity);
_takeMaintenance(tMaintenance);
_takeLiquidityWallet(tLiquidityWallet);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* TRANSFER (END)
*/
}
|
TRANSFER/indicates if fee should be deducted from transferif any account belongs to _isExcludedFromFee account then remove the fee if fees are calculated, then these amounts will be tracked in totalTokensTransferred[sender]
|
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
if(takeFee){
addTokensTransferred(from, amount);
}
}
| 1,000,509
|
pragma solidity ^0.4.21;
/*
* BeNow
*
* You are 100% responsible for auditing this contract code.
* If there's a flaw in this code and you lose ETH, you are 100% responsible.
*
*/
contract Hourglass {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends() > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "BeNOW";
string public symbol = "NOW";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 20;
uint8 constant internal developerFee_ = 2;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
address constant public developerFundAddress = 0xc22388e302ac17c7a2b87a9a3e7325febd4e2458;
uint256 public totalDevelopmentFundBalance;
uint256 public totalDevelopmentFundEarned;
bool firstBuy = true;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 3 ether;
uint256 constant internal ambassadorQuota_ = 40 ether;
// saved savedReferrals
mapping(address => address) internal savedReferrals_;
// total earned for referrals
mapping(address => uint256) internal totalEarned_;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Hourglass()
public
{
// add administrators here
administrators[developerFundAddress] = true;
ambassadors_[0xA36f907BE1FBf75e2495Cc87F8f4D201c1b634Af] = true;
ambassadors_[0x5Ec92834A6bc25Fe70DE9483F6F4B1051fcc0C96] = true;
ambassadors_[0xe8B1C589e86DEf7563aD43BebDDB7B1677beC9A9] = true;
ambassadors_[0x4da6fc68499FB3753e77DD6871F2A0e4DC02fEbE] = true;
ambassadors_[0x8E2a227eC573dd2Ef11c5B0B7985cb3d9ADf06b3] = true;
ambassadors_[0xD795b28e43a14d395DDF608eaC6906018e3AF0fC] = true;
ambassadors_[0xD01167b13444E3A75c415d644C832Ab8FC3fc742] = true;
ambassadors_[0x46091f77b224576E224796de5c50e8120Ad7D764] = true;
ambassadors_[0x871A93B4046545CCff4F1e41EedFC52A6acCbc42] = true;
ambassadors_[0xcbbcf632C87D3dF7342642525Cc5F30090E390a6] = true;
ambassadors_[0x025fb7cad32448571150de24ac254fe8d9c10c50] = true;
ambassadors_[0xe196F7c242dE1F42B10c262558712e6268834008] = true;
ambassadors_[0x4ffe17a2a72bc7422cb176bc71c04ee6d87ce329] = true;
ambassadors_[0x867e1996C36f57545C365B33edd48923873792F6] = true;
ambassadors_[0x1ef88e2858fb1052180e2a372d94f24bcb8cc5b0] = true;
ambassadors_[0x642e0Ce9AE8c0D8007e0ACAF82C8D716FF8c74c1] = true;
ambassadors_[0x26d8627dbFF586A3B769f34DaAd6085Ef13B2978] = true;
ambassadors_[0x9abcf6b5ae277c1a4a14f3db48c89b59d831dc8f] = true;
ambassadors_[0x847c5b4024C19547BCa7EFD503EbbB97f500f4C0] = true;
ambassadors_[0x19e361e3CF55bAD433Ed107997728849b172a139] = true;
ambassadors_[0x008ca4F1bA79D1A265617c6206d7884ee8108a78] = true;
ambassadors_[0xE7F53CE9421670AC2f11C5035E6f6f13d9829aa6] = true;
ambassadors_[0x63913b8B5C6438f23c986aD6FdF103523B17fb90] = true;
ambassadors_[0x43593BCFC24301da0763ED18845A120FaEC1EAfE] = true;
ambassadors_[0x87A7e71D145187eE9aAdc86954d39cf0e9446751] = true;
ambassadors_[0x7c76A64AC61D1eeaFE2B8AF6F7f0a6a1890418F3] = true;
ambassadors_[0xb0eF8673E22849bB45B3c97226C11a33394eEec1] = true;
ambassadors_[0xc585ca6a9B9C0d99457B401f8e2FD12048713cbc] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
require(msg.value >= .1 ether);
if(savedReferrals_[msg.sender] == 0x0000000000000000000000000000000000000000){
savedReferrals_[msg.sender] = _referredBy;
}else{
_referredBy = savedReferrals_[msg.sender];
}
purchaseTokens(msg.value, savedReferrals_[msg.sender]);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, savedReferrals_[msg.sender]);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokensWithoutDevelopmentFund(_dividends, savedReferrals_[msg.sender]);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Converts all of caller's affiliate rewards to tokens.
*/
function reinvestAffiliate()
public
{
require(referralBalance_[msg.sender] > 0);
// fetch rewards
uint256 _dividends = referralBalance_[msg.sender];
referralBalance_[msg.sender] = 0;
address _customerAddress = msg.sender;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokensWithoutDevelopmentFund(_dividends, savedReferrals_[msg.sender]);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Returns the saved referral.
*/
function getSavedReferral(address customer) public view returns (address) {
return savedReferrals_[customer];
}
/**
* Returns the total referral commision earned.
*/
function getTotalComission(address customer) public view returns (uint256) {
return totalEarned_[customer];
}
/**
* Returns the development fund balance.
*/
function getDevelopmentFundBalance() public view returns (uint256) {
return totalDevelopmentFundBalance;
}
/**
* Returns the total amount development fund has earned.
*/
function getTotalDevelopmentFundEarned() public view returns (uint256) {
return totalDevelopmentFundEarned;
}
/**
* Returns affiliate commision.
*/
function getReferralBalance() public view returns (uint256) {
return referralBalance_[msg.sender];
}
/**
* Withdraw development fund.
*/
function withdrawTotalDevEarned() public {
require(msg.sender == developerFundAddress);
developerFundAddress.transfer(totalDevelopmentFundBalance);
totalDevelopmentFundBalance = 0;
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
require(!onlyAmbassadors);
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Withdraws affiliate earnings
*/
function withdrawAffiliateRewards()
onlyStronghands()
public
{
require(!onlyAmbassadors);
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
require(_amountOfTokens >= 40 && !onlyAmbassadors);
if(ambassadors_[msg.sender] == true){
require(1529260200 < now);
}
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _devFund = SafeMath.div(SafeMath.mul(_ethereum, developerFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _devFund);
totalDevelopmentFundBalance = SafeMath.add(totalDevelopmentFundBalance, _devFund);
totalDevelopmentFundEarned = SafeMath.add(totalDevelopmentFundEarned, _devFund);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
if(ambassadors_[msg.sender] == true){
require(1529260200 < now);
}
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends() > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
*/
function myDividends()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _devFund = SafeMath.div(SafeMath.mul(_ethereum, developerFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _devFund);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _devFund = SafeMath.div(SafeMath.mul(_ethereum, developerFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _devFund);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _devFund = SafeMath.div(SafeMath.mul(_ethereumToSpend, developerFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _devFund);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _devFund = SafeMath.div(SafeMath.mul(_ethereum, developerFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _devFund);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
if(firstBuy == true){
require(msg.sender == 0xc585ca6a9B9C0d99457B401f8e2FD12048713cbc);
firstBuy = false;
}
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 5);
uint256 _devFund = SafeMath.div(SafeMath.mul(_incomingEthereum, developerFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _devFund);
totalDevelopmentFundBalance = SafeMath.add(totalDevelopmentFundBalance, _devFund);
totalDevelopmentFundEarned = SafeMath.add(totalDevelopmentFundEarned, _devFund);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
// add to stats
totalEarned_[_referredBy] = SafeMath.add(totalEarned_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
function purchaseTokensWithoutDevelopmentFund(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 5);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
// add to stats
totalEarned_[_referredBy] = SafeMath.add(totalEarned_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
Withdraws affiliate earnings/ setup data lambo delivery service fire event
|
function withdrawAffiliateRewards()
onlyStronghands()
public
{
require(!onlyAmbassadors);
address _customerAddress = msg.sender;
uint256 _dividends = referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
onWithdraw(_customerAddress, _dividends);
}
| 2,088,364
|
./partial_match/42/0xAE311d0b6302606F4927940158Aba7a2dbd22553/sources/DisposableGovernance.sol
|
Called by existed member if wish to switch membership to other address. _add address of user to forward membership./
|
function switchMembership(address _add) external {
require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add));
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.addToWhitelist(_add);
_updateRole(_add, uint(Role.Member), true);
tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender);
emit switchedMembership(msg.sender, _add, now);
}
| 3,432,997
|
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "contracts/libraries/Fixed.sol";
import "contracts/p0/RToken.sol";
import "contracts/p0/mixins/Component.sol";
import "contracts/p1/RToken.sol";
import "contracts/interfaces/IBackingManager.sol";
import "contracts/interfaces/IBasketHandler.sol";
import "contracts/plugins/mocks/ERC20Mock.sol";
import "contracts/fuzz/Mocks.sol";
import "contracts/fuzz/Utils.sol";
/* TODO: Here's a few of the many ways that this test could be improved:
- Decorate basically everything with events for clues about test failures
- Have the MockBasketHandler and MockBackingManager save an "event" log, representing the
state-change events that they've been issued, so that we can ensure the equivalence of the
function call sequence that each RToken emits
- Get these mocks to be more active, so they exercise more of the RToken space.
- In particular, make the referesher functions do more of what they're intended to do
- Have the mock contracts act wildly, possibly represented by more actions from the
RTokenDiffTest contract, to mock out changes that might effect the RToken (but that the
RToken probably doesn't model directly)
- Change the mock basket model from "token A" to "switches between token A and token B" or use
- Or something yet more ambitious? This could be practically anything we can drive from
random actions.
- It *might* be that these mocked-out component models are really useful for other fuzz tests too
*/
contract MockBackingManager is IBackingManager, ComponentMock {
function init(
IMain,
uint32,
uint192,
uint192,
uint192
) external {}
function grantRTokenAllowance(IERC20) external {}
function manageTokens(IERC20[] memory) external {}
/// Settle any auctions that can be settled
function settleTrade(IERC20) external virtual override {}
function claimAndSweepRewards() external virtual override {}
function trades(IERC20) external view virtual override returns (ITrade) {
return ITrade(address(0));
}
/// @return {%} The maximum trade slippage acceptable
function maxTradeSlippage() external view virtual override returns (uint192) {
return 1e16;
}
/// @return {UoA} The smallest amount of value worth trading
function dustAmount() external view virtual override returns (uint192) {
return 2e20;
}
}
contract MockBasketHandler is IBasketHandler, ComponentMock {
using FixLib for uint192;
/* The mock basket we're running with, here, is always either 100% A or 100% B.
* Each is always assumed to have a price of 1 UoA.
* We can (and maybe should) build something with wider behavior
*/
// Is the basket 100% A (instead of 100% B?)
bool public modeA = true;
IERC20 public tokenA;
IERC20 public tokenB;
uint256 public nonce = 0;
uint256 public timestamp;
constructor(IERC20 tokenA_, IERC20 tokenB_) {
tokenA = tokenA_;
tokenB = tokenB_;
timestamp = block.timestamp;
}
function init(IMain) external {}
function token() private view returns (IERC20) {
return modeA ? tokenA : tokenB;
}
/// Set the prime basket
function setPrimeBasket(IERC20[] memory, uint192[] memory) external {}
/// Set the backup configuration for a given target
function setBackupConfig(
bytes32,
uint256,
IERC20[] calldata
) external {}
/// Default the basket in order to schedule a basket refresh
function disableBasket() external {}
/// Governance-controlled setter to cause a basket switch explicitly
function refreshBasket() external {
// TODO: modeA = !modeA, and we do all the needed trades and handle capitalization
++nonce;
timestamp = block.timestamp;
}
/// @return If the BackingManager has sufficient collateral to redeem the entire RToken supply
function fullyCapitalized() external pure returns (bool) {
return true;
}
/// @return status The worst CollateralStatus of all collateral in the basket
function status() external pure returns (CollateralStatus) {
return CollateralStatus.SOUND;
}
/// @return {tok/BU} The whole token quantity of token in the reference basket
function quantity(IERC20 erc20) external view returns (uint192) {
return token() == erc20 ? FIX_ONE : FIX_ZERO;
}
/// @param amount {BU}
/// @return erc20s The addresses of the ERC20 tokens in the reference basket
/// @return quantities {qTok} The quantity of each ERC20 token to issue `amount` baskets
function quote(uint192 amount, RoundingMode rounding)
external
view
returns (address[] memory erc20s, uint256[] memory quantities)
{
erc20s = new address[](1);
erc20s[0] = modeA ? address(tokenA) : address(tokenB);
quantities = new uint256[](1);
quantities[0] = amount.shiftl(18).toUint(rounding);
}
/// @return baskets {BU} The quantity of complete baskets at an address. A balance for BUs
function basketsHeldBy(address acct) external view returns (uint192 baskets) {
int8 decimals = int8(IERC20Metadata(address(token())).decimals());
baskets = shiftl_toFix(token().balanceOf(acct), -decimals);
}
/// @return p {UoA/BU} The protocol's best guess at what a BU would be priced at in UoA
function price() external pure returns (uint192 p) {
return FIX_ONE;
}
/// @return nonce_ The basket nonce, a monotonically increasing unique identifier
/// @return timestamp_ The timestamp at which the basket was last set
function lastSet() external view returns (uint256 nonce_, uint256 timestamp_) {
nonce_ = nonce;
timestamp_ = timestamp;
}
}
contract RTokenTestSystem is MainMock {
using FixLib for uint192;
ERC20Mock public baseA;
ERC20Mock public baseB;
constructor(IRToken rToken_) {
DeploymentParams memory params = defaultParams();
Components memory components;
baseA = new ERC20Mock("Base Token A", "A$");
baseB = new ERC20Mock("Base Token B", "B$");
for (uint256 i = 0; i < USERS.length; i++) {
baseA.mint(USERS[i], 1e24);
baseB.mint(USERS[i], 1e24);
}
init(components, IERC20(address(0)), 0);
basketHandler = new MockBasketHandler(baseA, baseB);
basketHandler.init(this);
backingManager = new MockBackingManager();
backingManager.init(
this,
params.tradingDelay,
params.backingBuffer,
params.maxTradeSlippage,
params.dustAmount
);
rToken = rToken_;
rToken.init(this, "RToken", "RTK", "rtoken://1", params.issuanceRate);
}
}
contract RTokenP0Test is RTokenP0 {
function _msgSender() internal view virtual override returns (address) {
return MainMock(address(main)).sender();
}
}
contract RTokenP1Test is RTokenP1 {
function _msgSender() internal view virtual override returns (address) {
return MainMock(address(main)).sender();
}
}
contract RTokenDiffTest {
using FixLib for uint192;
address[] public USERS = [address(0x10000), address(0x20000), address(0x30000)];
RTokenTestSystem public p0;
RTokenTestSystem public p1;
modifier fromSender() {
p0.setSender(msg.sender);
p1.setSender(msg.sender);
_;
p0.setSender(address(0));
p1.setSender(address(0));
}
modifier fromBackingMgr() {
p0.setSender(address(p0.backingManager()));
p1.setSender(address(p1.backingManager()));
_;
p0.setSender(address(0));
p1.setSender(address(0));
}
constructor() {
p0 = new RTokenTestSystem(new RTokenP0Test());
p1 = new RTokenTestSystem(new RTokenP1Test());
}
// Actions and state modifiers
// ==== user actions, performed by 0x[123]0000. Melt
function issue(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().issue(amount);
p1.rToken().issue(amount);
}
function cancel(uint256 endId, bool e) external fromSender {
p0.rToken().cancel(endId, e);
p1.rToken().cancel(endId, e);
}
function vest(address acct, uint256 endId) external fromSender {
p0.rToken().vest(acct, endId);
p1.rToken().vest(acct, endId);
}
// TODO: Add "cancel" and "vest" variations that are likely to succeed too
// i.e, ones that have valid endIDs
function redeem(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().redeem(amount);
p1.rToken().redeem(amount);
}
function melt(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().melt(amount);
p1.rToken().melt(amount);
}
function mint(address recipient, uint256 amount) external fromBackingMgr {
amount %= 1e36;
recipient = address((uint160(recipient) % 3) * 0x10000); // mint only to USERS
p0.rToken().mint(recipient, amount);
p1.rToken().mint(recipient, amount);
}
function setBasketsNeeded(uint192 basketsNeeded) external fromBackingMgr {
basketsNeeded %= 1e36;
p0.rToken().setBasketsNeeded(basketsNeeded);
p1.rToken().setBasketsNeeded(basketsNeeded);
}
// Auth on these is that the caller needs to be main.owner. That... should be this contract?
function setIssuanceRate(uint192 val) external {
val %= 1e24;
assert(p0.owner() == address(this)); // hope but verify
assert(p1.owner() == address(this));
RTokenP0(address(p0.rToken())).setIssuanceRate(val);
RTokenP1(address(p1.rToken())).setIssuanceRate(val);
}
// TODO: changes to MockERC20 balances
// Invariant: the observable rtoken prices are equal
function echidna_prices_equal() external view returns (bool) {
return p0.rToken().price() == p1.rToken().price();
}
function echidna_vesting_ids_equal() external view returns (bool) {
return
p0.rToken().endIdForVest(USERS[0]) == p1.rToken().endIdForVest(USERS[0]) &&
p0.rToken().endIdForVest(USERS[1]) == p1.rToken().endIdForVest(USERS[1]) &&
p0.rToken().endIdForVest(USERS[2]) == p1.rToken().endIdForVest(USERS[2]);
}
function echidna_baskets_needed_equal() external view returns (bool) {
return p0.rToken().basketsNeeded() == p1.rToken().basketsNeeded();
}
function all_balances_equal(address acct0, address acct1) internal view returns (bool) {
return
p0.baseA().balanceOf(acct0) == p1.baseA().balanceOf(acct1) &&
p0.baseB().balanceOf(acct0) == p1.baseB().balanceOf(acct1) &&
p0.rToken().balanceOf(acct0) == p1.rToken().balanceOf(acct1);
}
function echidna_user_balances_equal() external view returns (bool equal) {
equal =
all_balances_equal(address(p0.backingManager()), address(p1.backingManager())) &&
all_balances_equal(address(p0.basketHandler()), address(p1.basketHandler())) &&
all_balances_equal(address(p0), address(p1));
for (uint256 i = 0; i < USERS.length; i++) {
equal = equal && all_balances_equal(USERS[i], USERS[i]);
}
}
}
|
return {tok/BU} The whole token quantity of token in the reference basket
|
function quantity(IERC20 erc20) external view returns (uint192) {
return token() == erc20 ? FIX_ONE : FIX_ZERO;
}
| 1,833,297
|
// BK Ok
pragma solidity 0.5.16;
/**
* @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.
*/
// BK Ok. Referenced in StakingContract
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
// BK Ok - Internal pure function
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// BK Ok
uint256 c = a + b;
// BK Ok
require(c >= a, "SafeMath: addition overflow");
// BK Ok
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.
*/
// BK Ok - Internal pure function
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// BK Ok - "overflow" => "underflow"
require(b <= a, "SafeMath: subtraction overflow");
// BK Ok
uint256 c = a - b;
// BK Ok
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
// BK NOTE - This function is unused
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, "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.
*/
// BK NOTE - This function is unused
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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.
*/
// BK NOTE - This function is unused
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
// BK Ok - Interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
// BK Ok - function totalSupply() public view returns (uint256)
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
// BK Ok - function balanceOf(address _owner) public view returns (uint256 balance)
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.
*/
// BK Ok - function transfer(address _to, uint256 _value) public returns (bool success)
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.
*/
// BK Ok - function allowance(address _owner, address _spender) public view returns (uint256 remaining)
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.
*
* > 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.
*/
// BK Ok - function approve(address _spender, uint256 _value) public returns (bool success)
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.
*/
// BK Ok - function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
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.
*/
// BK Ok - event Transfer(address indexed _from, address indexed _to, uint256 _value)
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.
*/
// BK Ok - event Approval(address indexed _owner, address indexed _spender, uint256 _value)
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// @title An interface for staking contracts which support stake migration.
// BK Ok
interface IMigratableStakingContract {
/// @dev Returns the address of the underlying staked token.
/// @return IERC20 The address of the token.
// BK Ok
function getToken() external view returns (IERC20);
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The number of tokens to stake.
// BK Ok
function acceptMigration(address _stakeOwner, uint256 _amount) external;
// BK Ok - Event
event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
}
/// @title An interface for staking contracts.
// BK Ok
interface IStakingContract {
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _amount uint256 The amount of tokens to stake.
// BK Ok
function stake(uint256 _amount) external;
/// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which
/// msg.sender would be able to withdraw all of his tokens.
/// @param _amount uint256 The amount of tokens to unstake.
// BK Ok
function unstake(uint256 _amount) external;
/// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS
/// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was
/// requested to release all stakes).
// BK Ok
function withdraw() external;
/// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender.
// BK Ok
function restake() external;
/// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method
/// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a
/// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that
/// callers will be able to properly batch/paginate their requests.
/// @param _totalAmount uint256 The total amount of rewards to distributes.
/// @param _stakeOwners address[] The addresses of the stake owners.
/// @param _amounts uint256[] The amounts of the rewards.
// BK Ok
function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external;
/// @dev Returns the stake of the specified stake owner (excluding unstaked tokens).
/// @param _stakeOwner address The address to check.
/// @return uint256 The total stake.
// BK Ok
function getStakeBalanceOf(address _stakeOwner) external view returns (uint256);
/// @dev Returns the total amount staked tokens (excluding unstaked tokens).
/// @return uint256 The total staked tokens of all stake owners.
// BK Ok
function getTotalStakedTokens() external view returns (uint256);
/// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released.
/// @param _stakeOwner address The address to check.
/// @return cooldownAmount uint256 The total tokens in cooldown.
/// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds).
// BK Ok
function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount,
uint256 cooldownEndTime);
/// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract.
/// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration.
/// @param _amount uint256 The amount of tokens to migrate.
// BK Ok
function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external;
// BK Next 5 Ok
event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
}
/// @title An interface for notifying of stake change events (e.g., stake, unstake, partial unstake, restate, etc.).
// BK Ok - Assuming `notifier` is set to `0x0000000000000000000000000000000000000000`
interface IStakeChangeNotifier {
/// @dev Notifies of stake change event.
/// @param _stakeOwner address The address of the subject stake owner.
/// @param _amount uint256 The difference in the total staked amount.
/// @param _sign bool The sign of the added (true) or subtracted (false) amount.
/// @param _updatedStake uint256 The updated total staked amount.
// BK Ok
function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) external;
/// @dev Notifies of multiple stake change events.
/// @param _stakeOwners address[] The addresses of subject stake owners.
/// @param _amounts uint256[] The differences in total staked amounts.
/// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts.
/// @param _updatedStakes uint256[] The updated total staked amounts.
// BK Ok
function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs,
uint256[] calldata _updatedStakes) external;
/// @dev Notifies of stake migration event.
/// @param _stakeOwner address The address of the subject stake owner.
/// @param _amount uint256 The migrated amount.
// BK Ok
function stakeMigration(address _stakeOwner, uint256 _amount) external;
}
/// @title Orbs staking smart contract.
contract StakingContract is IStakingContract, IMigratableStakingContract {
// BK Ok
using SafeMath for uint256;
// BK Ok
struct Stake {
uint256 amount;
uint256 cooldownAmount;
uint256 cooldownEndTime;
}
// BK Ok
struct WithdrawResult {
uint256 withdrawnAmount;
uint256 stakedAmount;
uint256 stakedAmountDiff;
}
// The version of the smart contract.
// BK Ok - Not referenced in this smart contract
uint public constant VERSION = 1;
// The maximum number of approved staking contracts as migration destinations.
// BK Ok - Referenced in addMigrationDestination()
uint public constant MAX_APPROVED_STAKING_CONTRACTS = 10;
// The mapping between stake owners and their data.
// BK Ok
mapping(address => Stake) internal stakes;
// Total amount of staked tokens (not including unstaked tokes in cooldown or pending withdrawal).
// BK Ok
uint256 internal totalStakedTokens;
// The period (in seconds) between a stake owner's request to stop staking and being able to withdraw them.
// BK Ok
uint256 public cooldownPeriodInSec;
// The address responsible for managing migration to a new staking contract.
// BK Ok - Set in constructor() and setMigrationManager()
address public migrationManager;
// The address responsible for emergency operations and graceful return of staked tokens back to their owners.
// BK Ok - Set in constructor() and setEmergencyManager()
address public emergencyManager;
// The list of staking contracts that are approved by this contract. It would be only allowed to migrate a stake to
// one of these contracts.
// BK Ok - Written by approvedStakingContracts() and removeMigrationDestination(). Read by findApprovedStakingContractIndex()
IMigratableStakingContract[] public approvedStakingContracts;
// The address of the contract responsible for publishing stake change notifications.
// BK Ok - Assuming `notifier` is set to 0x0000000000000000000000000000000000000000 . IStakeChangeNotifier implementation will have to be separately audited before usage with this contract
IStakeChangeNotifier public notifier;
// The address of the ORBS token.
// BK Ok
IERC20 internal token;
// Represents whether the contract accepts new staking requests. Please note, that even when it's turned off,
// it'd be still possible to unstake or withdraw tokens.
//
// Note: This can be turned off only once by the emergency manager of the contract.
// BK Ok - Can only be switched off in `stopAcceptingNewStakes()`, executed by `emergencyManager`
bool public acceptingNewStakes = true;
// Represents whether this staking contract allows releasing all unstaked tokens unconditionally. When it's turned
// on, stake owners could release their staked tokens, without explicitly requesting to unstake them, and their
// previously unstaked tokens, regardless of the cooldown period. This also stops the contract from accepting new
// stakes.
//
// Note: This can be turned off only once by the emergency manager of the contract.
// BK Ok - Can only be switched on in `releaseAllStakes()`, executed by `emergencyManager`
bool public releasingAllStakes = false;
// BK Next 7 Ok
event MigrationManagerUpdated(address indexed migrationManager);
event MigrationDestinationAdded(IMigratableStakingContract indexed stakingContract);
event MigrationDestinationRemoved(IMigratableStakingContract indexed stakingContract);
event EmergencyManagerUpdated(address indexed emergencyManager);
event StakeChangeNotifierUpdated(IStakeChangeNotifier indexed notifier);
event StoppedAcceptingNewStake();
event ReleasedAllStakes();
// BK Ok - Modifier for setMigrationManager(), setStakeChangeNotifier(), addMigrationDestination() and removeMigrationDestination()
modifier onlyMigrationManager() {
// BK Ok
require(msg.sender == migrationManager, "StakingContract: caller is not the migration manager");
// BK Ok
_;
}
// BK Ok - Modifier for setEmergencyManager(), stopAcceptingNewStakes() and releaseAllStakes()
modifier onlyEmergencyManager() {
// BK Ok
require(msg.sender == emergencyManager, "StakingContract: caller is not the emergency manager");
// BK Ok
_;
}
// BK Ok - Modifier for stake(), restake(), acceptMigration(), distributeRewards() and stopAcceptingNewStakes()
modifier onlyWhenAcceptingNewStakes() {
// BK Ok
require(acceptingNewStakes && !releasingAllStakes, "StakingContract: not accepting new stakes");
// BK Ok
_;
}
// BK Ok - Modifier for withdrawReleasedStakes()
modifier onlyWhenStakesReleased() {
// BK Ok
require(releasingAllStakes, "StakingContract: not releasing all stakes");
// BK Ok
_;
}
// BK Ok - Modifier for migrateStakedTokens() and releaseAllStakes()
modifier onlyWhenStakesNotReleased() {
// BK Ok
require(!releasingAllStakes, "StakingContract: releasing all stakes");
// BK Ok
_;
}
/// @dev Initializes the staking contract.
/// @param _cooldownPeriodInSec uint256 The period (in seconds) between a stake owner's request to stop staking and being
/// able to withdraw them.
/// @param _migrationManager address The address responsible for managing migration to a new staking contract.
/// @param _emergencyManager address The address responsible for emergency operations and graceful return of staked
/// tokens back to their owners.
/// @param _token IERC20 The address of the ORBS token.
// BK Ok - Can only be called once per contract deployment
constructor(uint256 _cooldownPeriodInSec, address _migrationManager, address _emergencyManager, IERC20 _token) public {
// BK Next 4 Ok
require(_cooldownPeriodInSec > 0, "StakingContract::ctor - cooldown period must be greater than 0");
require(_migrationManager != address(0), "StakingContract::ctor - migration manager must not be 0");
require(_emergencyManager != address(0), "StakingContract::ctor - emergency manager must not be 0");
require(address(_token) != address(0), "StakingContract::ctor - ORBS token must not be 0");
// BK Next 4 Ok
cooldownPeriodInSec = _cooldownPeriodInSec;
migrationManager = _migrationManager;
emergencyManager = _emergencyManager;
token = _token;
}
/// @dev Sets the address of the migration manager.
/// @param _newMigrationManager address The address of the new migration manager.
// BK Ok - External function, can only be executed by `migrationManager`
function setMigrationManager(address _newMigrationManager) external onlyMigrationManager {
// BK Next 2 Ok
require(_newMigrationManager != address(0), "StakingContract::setMigrationManager - address must not be 0");
require(migrationManager != _newMigrationManager,
"StakingContract::setMigrationManager - address must be different than the current address");
// BK Ok
migrationManager = _newMigrationManager;
// BK Ok - event MigrationManagerUpdated(address indexed migrationManager);
emit MigrationManagerUpdated(_newMigrationManager);
}
/// @dev Sets the address of the emergency manager.
/// @param _newEmergencyManager address The address of the new emergency manager.
// BK Ok - External function, can only be executed by `emergencyManager`
function setEmergencyManager(address _newEmergencyManager) external onlyEmergencyManager {
// BK Next 2 Ok
require(_newEmergencyManager != address(0), "StakingContract::setEmergencyManager - address must not be 0");
require(emergencyManager != _newEmergencyManager,
"StakingContract::setEmergencyManager - address must be different than the current address");
// BK Ok
emergencyManager = _newEmergencyManager;
// BK Ok - event EmergencyManagerUpdated(address indexed emergencyManager);
emit EmergencyManagerUpdated(_newEmergencyManager);
}
/// @dev Sets the address of the stake change notifier contract.
/// @param _newNotifier IStakeChangeNotifier The address of the new stake change notifier contract.
///
/// Note: it's allowed to reset the notifier to a zero address.
// BK Ok - External function, can only be called by `migrationManager`. Can set to 0x0000000000000000000000000000000000000000
function setStakeChangeNotifier(IStakeChangeNotifier _newNotifier) external onlyMigrationManager {
// BK Ok
require(notifier != _newNotifier,
"StakingContract::setStakeChangeNotifier - address must be different than the current address");
// BK Ok
notifier = _newNotifier;
// BK Ok - event StakeChangeNotifierUpdated(IStakeChangeNotifier indexed notifier);
emit StakeChangeNotifierUpdated(notifier);
}
/// @dev Adds a new contract to the list of approved staking contracts migration destinations.
/// @param _newStakingContract IMigratableStakingContract The new contract to add.
// BK Ok - External function, can only be called by migrationManager
function addMigrationDestination(IMigratableStakingContract _newStakingContract) external onlyMigrationManager {
// BK Ok
require(address(_newStakingContract) != address(0),
"StakingContract::addMigrationDestination - address must not be 0");
// BK Ok
uint length = approvedStakingContracts.length;
// BK Ok - (length + 1) <= 10
require(length + 1 <= MAX_APPROVED_STAKING_CONTRACTS,
"StakingContract::addMigrationDestination - can't add more staking contracts");
// Check for duplicates.
// BK Ok
for (uint i = 0; i < length; ++i) {
// BK Ok
require(approvedStakingContracts[i] != _newStakingContract,
"StakingContract::addMigrationDestination - can't add a duplicate staking contract");
}
// BK Ok
approvedStakingContracts.push(_newStakingContract);
// BK Ok - event MigrationDestinationAdded(IMigratableStakingContract indexed stakingContract);
emit MigrationDestinationAdded(_newStakingContract);
}
/// @dev Removes a contract from the list of approved staking contracts migration destinations.
/// @param _stakingContract IMigratableStakingContract The contract to remove.
// BK Ok - External function, can only be called by migrationManager
function removeMigrationDestination(IMigratableStakingContract _stakingContract) external onlyMigrationManager {
// BK Ok
require(address(_stakingContract) != address(0),
"StakingContract::removeMigrationDestination - address must not be 0");
// Check for existence.
// BK Ok
(uint i, bool exists) = findApprovedStakingContractIndex(_stakingContract);
// BK Ok
require(exists, "StakingContract::removeMigrationDestination - staking contract doesn't exist");
// Swap the requested element with the last element and then delete it using pop/
// BK Next 2 Ok
approvedStakingContracts[i] = approvedStakingContracts[approvedStakingContracts.length - 1];
approvedStakingContracts.pop();
// BK Ok - event MigrationDestinationRemoved(IMigratableStakingContract indexed stakingContract);
emit MigrationDestinationRemoved(_stakingContract);
}
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _amount uint256 The amount of tokens to stake.
// BK NOTE - function stake(uint256 _amount) external;
// BK Ok - Any user can stake tokens already approve(...)-d to this contract
function stake(uint256 _amount) external onlyWhenAcceptingNewStakes {
// BK Ok
address stakeOwner = msg.sender;
// BK Ok
uint256 totalStakedAmount = stake(stakeOwner, _amount);
// BK Ok - event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit Staked(stakeOwner, _amount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChange(stakeOwner, _amount, true, totalStakedAmount);
}
/// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which
/// msg.sender would be able to withdraw all of his tokens.
/// @param _amount uint256 The amount of tokens to unstake.
// BK NOTE - function unstake(uint256 _amount) external;
// BK Ok - Any user can unstake tokens already staked
function unstake(uint256 _amount) external {
// BK Ok
require(_amount > 0, "StakingContract::unstake - amount must be greater than 0");
// BK Ok
address stakeOwner = msg.sender;
// BK Ok
Stake storage stakeData = stakes[stakeOwner];
// BK Next 3 Ok
uint256 stakedAmount = stakeData.amount;
uint256 cooldownAmount = stakeData.cooldownAmount;
uint256 cooldownEndTime = stakeData.cooldownEndTime;
// BK Ok
require(_amount <= stakedAmount, "StakingContract::unstake - can't unstake more than the current stake");
// If any tokens in cooldown are ready for withdrawal - revert. Stake owner should withdraw their unstaked
// tokens first.
require(cooldownAmount == 0 || cooldownEndTime > now,
"StakingContract::unstake - unable to unstake when there are tokens pending withdrawal");
// Update the amount of tokens in cooldown. Please note that this will also restart the cooldown period of all
// tokens in cooldown.
// BK Next 3 Ok
stakeData.amount = stakedAmount.sub(_amount);
stakeData.cooldownAmount = cooldownAmount.add(_amount);
stakeData.cooldownEndTime = now.add(cooldownPeriodInSec);
// BK Ok
totalStakedTokens = totalStakedTokens.sub(_amount);
// BK Ok
uint256 totalStakedAmount = stakeData.amount;
// BK Ok - event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit Unstaked(stakeOwner, _amount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChange(stakeOwner, _amount, false, totalStakedAmount);
}
/// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS
/// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was
/// requested to release all stakes).
// BK NOTE - function withdraw() external;
// BK Ok - Any account with unstaked tokens can withdraw unstaked tokens after cooldown period. If after all stakes released, both staked and unstaked tokens are withdrawn
function withdraw() external {
// BK Ok
address stakeOwner = msg.sender;
// BK NOTE - struct WithdrawResult {
// BK NOTE - uint256 withdrawnAmount;
// BK NOTE - uint256 stakedAmount;
// BK NOTE - uint256 stakedAmountDiff;
// BK NOTE - }
// BK Ok
WithdrawResult memory res = withdraw(stakeOwner);
// BK Ok - event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount);
// Trigger staking state change notifications only if the staking amount was changed.
// BK Ok
if (res.stakedAmountDiff == 0) {
// BK Ok
return;
}
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChange(stakeOwner, res.stakedAmountDiff, false, res.stakedAmount);
}
/// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender.
// BK NOTE - function restake() external;
// BK Ok - Any account with unstaked tokens in the cooldown period, or outside the cooldown period, can restake these tokens
function restake() external onlyWhenAcceptingNewStakes {
// BK Next 3 Ok
address stakeOwner = msg.sender;
Stake storage stakeData = stakes[stakeOwner];
uint256 cooldownAmount = stakeData.cooldownAmount;
// BK Ok
require(cooldownAmount > 0, "StakingContract::restake - no unstaked tokens");
// BK Next 3 Ok
stakeData.amount = stakeData.amount.add(cooldownAmount);
stakeData.cooldownAmount = 0;
stakeData.cooldownEndTime = 0;
// BK Ok
totalStakedTokens = totalStakedTokens.add(cooldownAmount);
// BK Ok
uint256 totalStakedAmount = stakeData.amount;
// BK Ok - event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit Restaked(stakeOwner, cooldownAmount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChange(stakeOwner, cooldownAmount, true, totalStakedAmount);
}
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The amount of tokens to stake.
// BK NOTE - function acceptMigration(address _stakeOwner, uint256 _amount) external;
// BK NOTE - msg.sender will be the new instance of this contract
// BK NOTE - If an account executes this directly, the effects are the same as executing stake(uint256), & different events emitted
// BK NOTE - State will throw if there is an error
// BK Ok
function acceptMigration(address _stakeOwner, uint256 _amount) external onlyWhenAcceptingNewStakes {
uint256 totalStakedAmount = stake(_stakeOwner, _amount);
// BK NOTE - event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit AcceptedMigration(_stakeOwner, _amount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChange(_stakeOwner, _amount, true, totalStakedAmount);
}
/// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract.
/// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration.
/// @param _amount uint256 The amount of tokens to migrate.
// BK NOTE - function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external;
function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external
onlyWhenStakesNotReleased {
// BK Next 2 Ok
require(isApprovedStakingContract(_newStakingContract),
"StakingContract::migrateStakedTokens - migration destination wasn't approved");
require(_amount > 0, "StakingContract::migrateStakedTokens - amount must be greater than 0");
// BK Next 3 Ok
address stakeOwner = msg.sender;
Stake storage stakeData = stakes[stakeOwner];
uint256 stakedAmount = stakeData.amount;
// BK Next 2 Ok
require(stakedAmount > 0, "StakingContract::migrateStakedTokens - no staked tokens");
require(_amount <= stakedAmount, "StakingContract::migrateStakedTokens - amount exceeds staked token balance");
// BK Ok
stakeData.amount = stakedAmount.sub(_amount);
// BK Ok
totalStakedTokens = totalStakedTokens.sub(_amount);
// BK Ok
require(_newStakingContract.getToken() == token,
"StakingContract::migrateStakedTokens - staked tokens must be the same");
// BK Ok
require(token.approve(address(_newStakingContract), _amount),
"StakingContract::migrateStakedTokens - couldn't approve transfer");
// BK Ok - event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit MigratedStake(stakeOwner, _amount, stakeData.amount);
// BK Ok - `acceptMigration(...)` -> `stake(...)` that will throw if the transfer fails
_newStakingContract.acceptMigration(stakeOwner, _amount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeMigration(stakeOwner, _amount);
}
/// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method
/// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a
/// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that
/// callers will be able to batch/paginate their requests properly.
/// @param _totalAmount uint256 The total amount of rewards to distributes.
/// @param _stakeOwners address[] The addresses of the stake owners.
/// @param _amounts uint256[] The amounts of the rewards.
// BK NOTE - function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external;
// BK Ok
function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external
onlyWhenAcceptingNewStakes {
// BK Ok
require(_totalAmount > 0, "StakingContract::distributeRewards - total amount must be greater than 0");
// BK Next 2 Ok
uint256 stakeOwnersLength = _stakeOwners.length;
uint256 amountsLength = _amounts.length;
// BK Next 2 Ok
require(stakeOwnersLength > 0 && amountsLength > 0,
"StakingContract::distributeRewards - lists can't be empty");
require(stakeOwnersLength == amountsLength,
"StakingContract::distributeRewards - lists must be of the same size");
// Transfer all the tokens to the smart contract and update the stake owners list accordingly.
// BK Ok
require(token.transferFrom(msg.sender, address(this), _totalAmount),
"StakingContract::distributeRewards - insufficient allowance");
// BK Next 2 Ok
bool[] memory signs = new bool[](amountsLength);
uint256[] memory totalStakedAmounts = new uint256[](amountsLength);
// BK Ok
uint256 expectedTotalAmount = 0;
// BK Ok
for (uint i = 0; i < stakeOwnersLength; ++i) {
// BK Next 2 Ok
address stakeOwner = _stakeOwners[i];
uint256 amount = _amounts[i];
// BK Next 2 Ok
require(stakeOwner != address(0), "StakingContract::distributeRewards - stake owner can't be 0");
require(amount > 0, "StakingContract::distributeRewards - amount must be greater than 0");
// BK Next 2 Ok
Stake storage stakeData = stakes[stakeOwner];
stakeData.amount = stakeData.amount.add(amount);
// BK Ok
expectedTotalAmount = expectedTotalAmount.add(amount);
// BK Next 3 Ok
uint256 totalStakedAmount = stakeData.amount;
signs[i] = true;
totalStakedAmounts[i] = totalStakedAmount;
// BK NOTE - event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
// BK Ok
emit Staked(stakeOwner, amount, totalStakedAmount);
}
// BK Ok
require(_totalAmount == expectedTotalAmount, "StakingContract::distributeRewards - incorrect total amount");
// BK Ok
totalStakedTokens = totalStakedTokens.add(_totalAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChangeBatch(_stakeOwners, _amounts, signs, totalStakedAmounts);
}
/// @dev Returns the stake of the specified stake owner (excluding unstaked tokens).
/// @param _stakeOwner address The address to check.
/// @return uint256 The stake of the stake owner.
// BK NOTE - function getStakeBalanceOf(address _stakeOwner) external view returns (uint256);
// BK Ok - External view function
function getStakeBalanceOf(address _stakeOwner) external view returns (uint256) {
// BK Ok
return stakes[_stakeOwner].amount;
}
/// @dev Returns the total amount staked tokens (excluding unstaked tokens).
/// @return uint256 The total staked tokens of all stake owners.
// BK NOTE - function getTotalStakedTokens() external view returns (uint256);
// BK Ok - External view function
function getTotalStakedTokens() external view returns (uint256) {
// BK Ok
return totalStakedTokens;
}
/// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released.
/// @param _stakeOwner address The address to check.
/// @return cooldownAmount uint256 The total tokens in cooldown.
/// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds).
// BK NOTE - function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime);
// BK Ok - External view function
function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount,
uint256 cooldownEndTime) {
Stake memory stakeData = stakes[_stakeOwner];
cooldownAmount = stakeData.cooldownAmount;
cooldownEndTime = stakeData.cooldownEndTime;
}
/// @dev Returns the address of the underlying staked token.
/// @return IERC20 The address of the token.
// BK NOTE - function getToken() external view returns (IERC20);
// BK Ok - External view function
function getToken() external view returns (IERC20) {
// BK Ok
return token;
}
/// @dev Requests the contract to stop accepting new staking requests.
// BK Ok - External function that can only be executed by `emergencyManager`
function stopAcceptingNewStakes() external onlyEmergencyManager onlyWhenAcceptingNewStakes {
// BK Ok
acceptingNewStakes = false;
// BK Ok - event StoppedAcceptingNewStake();
emit StoppedAcceptingNewStake();
}
/// @dev Requests the contract to release all stakes.
// BK Ok - External function that can only be executed by `emergencyManager`
function releaseAllStakes() external onlyEmergencyManager onlyWhenStakesNotReleased {
// BK Ok
releasingAllStakes = true;
// BK Ok - event ReleasedAllStakes();
emit ReleasedAllStakes();
}
/// @dev Requests withdraw of released tokens for a list of addresses.
/// @param _stakeOwners address[] The addresses of the stake owners.
// BK NOTE - Can hit gas limit for many `_stakeOwners`, but caller can adjust batch size
// BK Ok - Any account can execute on behalf of any other accounts with staked and/or unstaked tokens, after `emergencyManager` executes `releaseAllStakes()`
function withdrawReleasedStakes(address[] calldata _stakeOwners) external onlyWhenStakesReleased {
// BK Ok
uint256 stakeOwnersLength = _stakeOwners.length;
// BK Ok
uint256[] memory stakedAmountDiffs = new uint256[](stakeOwnersLength);
// BK Ok
bool[] memory signs = new bool[](stakeOwnersLength);
// BK Ok
uint256[] memory totalStakedAmounts = new uint256[](stakeOwnersLength);
// BK Ok
for (uint i = 0; i < stakeOwnersLength; ++i) {
// BK Ok
address stakeOwner = _stakeOwners[i];
// BK NOTE - struct WithdrawResult {
// BK NOTE - uint256 withdrawnAmount;
// BK NOTE - uint256 stakedAmount;
// BK NOTE - uint256 stakedAmountDiff;
// BK NOTE - }
// BK Ok
WithdrawResult memory res = withdraw(stakeOwner);
// BK Next 3 Ok
stakedAmountDiffs[i] = res.stakedAmountDiff;
signs[i] = false;
totalStakedAmounts[i] = res.stakedAmount;
// BK Ok - event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount);
}
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
// BK Ok
stakeChangeBatch(_stakeOwners, stakedAmountDiffs, signs, totalStakedAmounts);
}
/// @dev Returns whether a specific staking contract was approved as a migration destination.
/// @param _stakingContract IMigratableStakingContract The staking contract to look for.
/// @return exists bool The approval status.
// BK NOTE - Called by migrateStakedTokens()
// BK Ok - Public view function
function isApprovedStakingContract(IMigratableStakingContract _stakingContract) public view returns (bool exists) {
// BK Ok
(, exists) = findApprovedStakingContractIndex(_stakingContract);
}
/// @dev Returns whether stake change notification is enabled.
// BK NOTE - Called by stakeChange(), stakeChangeBatch() and stakeMigration
// BK Ok - View internal function
function shouldNotifyStakeChange() view internal returns (bool) {
// BK Ok
return address(notifier) != address(0);
}
/// @dev Notifies of stake change events.
/// @param _stakeOwner address The address of the subject stake owner.
/// @param _amount int256 The difference in the total staked amount.
/// @param _sign bool The sign of the added (true) or subtracted (false) amount.
/// @param _updatedStake uint256 The updated total staked amount.
// BK Ok
function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) internal {
// BK Ok
if (!shouldNotifyStakeChange()) {
// BK Ok
return;
}
// BK NOTE - function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) external;
// BK Ok - Invalid `notifier` can cause an exception
notifier.stakeChange(_stakeOwner, _amount, _sign, _updatedStake);
}
/// @dev Notifies of multiple stake change events.
/// @param _stakeOwners address[] The addresses of subject stake owners.
/// @param _amounts uint256[] The differences in total staked amounts.
/// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts.
/// @param _updatedStakes uint256[] The updated total staked amounts.
// BK Ok
function stakeChangeBatch(address[] memory _stakeOwners, uint256[] memory _amounts, bool[] memory _signs,
uint256[] memory _updatedStakes) internal {
// BK Ok
if (!shouldNotifyStakeChange()) {
// BK Ok
return;
}
// BK NOTE - function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs,
// BK Ok - Invalid `notifier` can cause an exception
notifier.stakeChangeBatch(_stakeOwners, _amounts, _signs, _updatedStakes);
}
/// @dev Notifies of stake migration event.
/// @param _stakeOwner address The address of the subject stake owner.
/// @param _amount uint256 The migrated amount.
// BK Ok
function stakeMigration(address _stakeOwner, uint256 _amount) internal {
// BK Ok
if (!shouldNotifyStakeChange()) {
// BK Ok
return;
}
// BK NOTE - function stakeMigration(address _stakeOwner, uint256 _amount) external;
// BK Ok - Invalid `notifier` can cause an exception
notifier.stakeMigration(_stakeOwner, _amount);
}
/// @dev Stakes amount of ORBS tokens on behalf of the specified stake owner.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The amount of tokens to stake.
/// @return totalStakedAmount uint256 The total stake of the stake owner.
// BK NOTE - Called by stake() and acceptMigration()
// BK Ok - Private function callable by any account with tokens approved to this contract
function stake(address _stakeOwner, uint256 _amount) private returns (uint256 totalStakedAmount) {
// BK Next 2 Ok
require(_stakeOwner != address(0), "StakingContract::stake - stake owner can't be 0");
require(_amount > 0, "StakingContract::stake - amount must be greater than 0");
// BK Ok - storage
Stake storage stakeData = stakes[_stakeOwner];
// BK Ok
stakeData.amount = stakeData.amount.add(_amount);
// BK Ok
totalStakedTokens = totalStakedTokens.add(_amount);
// BK Ok
totalStakedAmount = stakeData.amount;
// Transfer the tokens to the smart contract and update the stake owners list accordingly.
// BK NOTE - Tokens are transferred from `msg.sender` while the accounting is done with `stakeOwner`
// BK NOTE - Does not matter with `stake(uint256)`, but can be different if an account directly calls `acceptMigration(...)` but this is not an expected use case
// BK Ok
require(token.transferFrom(msg.sender, address(this), _amount),
"StakingContract::stake - insufficient allowance");
}
/// @dev Requests to withdraw all of staked ORBS tokens back to the specified stake owner. Stake owners can withdraw
/// their ORBS tokens only after previously unstaking them and after the cooldown period has passed (unless the
/// contract was requested to release all stakes).
/// @return res WithdrawResult The result of the withdraw operation.
// BK NOTE - struct WithdrawResult {
// BK NOTE - uint256 withdrawnAmount;
// BK NOTE - uint256 stakedAmount;
// BK NOTE - uint256 stakedAmountDiff;
// BK NOTE - }
// BK Ok - Private function called by withdraw() and withdrawReleasedStakes()
function withdraw(address _stakeOwner) private returns (WithdrawResult memory res) {
// BK Ok
require(_stakeOwner != address(0), "StakingContract::withdraw - stake owner can't be 0");
// BK Ok - storage
Stake storage stakeData = stakes[_stakeOwner];
// BK Next 3 Ok
res.stakedAmount = stakeData.amount;
res.withdrawnAmount = stakeData.cooldownAmount;
res.stakedAmountDiff = 0;
// BK Ok
if (!releasingAllStakes) {
// BK Next 2 OK
require(res.withdrawnAmount > 0, "StakingContract::withdraw - no unstaked tokens");
require(stakeData.cooldownEndTime <= now, "StakingContract::withdraw - tokens are still in cooldown");
} else {
// If the contract was requested to release all stakes - allow to withdraw all staked and unstaked tokens.
// BK Next 2 Ok
res.withdrawnAmount = res.withdrawnAmount.add(res.stakedAmount);
res.stakedAmountDiff = res.stakedAmount;
// BK Ok
require(res.withdrawnAmount > 0, "StakingContract::withdraw - no staked or unstaked tokens");
// BK Ok
stakeData.amount = 0;
// BK Ok
totalStakedTokens = totalStakedTokens.sub(res.stakedAmount);
// BK Ok
res.stakedAmount = 0;
}
// BK Next 2 Ok
stakeData.cooldownAmount = 0;
stakeData.cooldownEndTime = 0;
// BK Ok
require(token.transfer(_stakeOwner, res.withdrawnAmount),
"StakingContract::withdraw - couldn't transfer stake");
}
/// @dev Returns an index of an existing approved staking contract.
/// @param _stakingContract IMigratableStakingContract The staking contract to look for.
/// @return index uint The index of the located staking contract (in the case that it was found).
/// @return exists bool The search result.
// BK NOTE - Called by removeMigrationDestination() and isApprovedStakingContract()
// BK Ok - Private view function
function findApprovedStakingContractIndex(IMigratableStakingContract _stakingContract) private view returns
(uint index, bool exists) {
// BK Ok
uint length = approvedStakingContracts.length;
// BK Ok
for (index = 0; index < length; ++index) {
// BK Ok
if (approvedStakingContracts[index] == _stakingContract) {
// BK Ok
exists = true;
// BK Ok
return (index, exists);
}
}
// BK OK - Should return (index = length, exist = false)
exists = false;
}
}
|
Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least the required amount using ERC20 approve. _stakeOwner address The specified stake owner. _amount uint256 The amount of tokens to stake. BK NOTE - function acceptMigration(address _stakeOwner, uint256 _amount) external; BK NOTE - msg.sender will be the new instance of this contract BK NOTE - If an account executes this directly, the effects are the same as executing stake(uint256), & different events emitted BK NOTE - State will throw if there is an error BK Ok BK NOTE - event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); Note: we aren't concerned with reentrancy since: 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. 2. The notifier is set and managed by the migration manager. BK Ok
|
function acceptMigration(address _stakeOwner, uint256 _amount) external onlyWhenAcceptingNewStakes {
uint256 totalStakedAmount = stake(_stakeOwner, _amount);
emit AcceptedMigration(_stakeOwner, _amount, totalStakedAmount);
stakeChange(_stakeOwner, _amount, true, totalStakedAmount);
}
| 13,011,268
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./InterfaceBabyTigers.sol";
contract BabyTigersManager is ReentrancyGuard, Ownable {
// Contracts
address public babyTigersAddress;
InterfaceBabyTigers babyTigersContract;
address public typicalTigersAddress;
IERC721Enumerable typicalTigersContract;
// Sale Status
bool public holderSaleIsActive = false;
mapping(uint256 => bool) public claimedTypicalTigers;
// Events
event HolderSaleActivation(bool isActive);
event BabyTigersManagerChanged(address newManager);
constructor(address _typicalTigersAddress, address _babyTigersAddress) {
babyTigersAddress = _babyTigersAddress;
babyTigersContract = InterfaceBabyTigers(_babyTigersAddress);
typicalTigersAddress = _typicalTigersAddress;
typicalTigersContract = IERC721Enumerable(_typicalTigersAddress);
}
//Holder status validation
function isTypicalTigerAvailable(uint256 _tokenId) public view returns(bool) {
bool isAvailableOnBabyTigersContract = babyTigersContract.isTypicalTigerAvailable(_tokenId);
return claimedTypicalTigers[_tokenId] != true && isAvailableOnBabyTigersContract;
}
// Minting
function ownerMint(address _to, uint256 _count) external onlyOwner {
babyTigersContract.ownerMint(_to, _count);
}
function holderMint(uint256[] calldata _typicalTigerIds, uint256 _count) external nonReentrant {
require(holderSaleIsActive, "HOLDER_SALE_INACTIVE");
require(
_count == _typicalTigerIds.length,
"INSUFFICIENT_TT_TOKENS"
);
require(typicalTigersContract.balanceOf(msg.sender) > 0, "NO_TT_TOKENS");
for (uint256 i = 0; i < _typicalTigerIds.length; i++) {
require(isTypicalTigerAvailable(_typicalTigerIds[i]), "TT_ALREADY_CLAIMED");
require(typicalTigersContract.ownerOf(_typicalTigerIds[i]) == msg.sender, "NOT_TT_OWNER");
claimedTypicalTigers[_typicalTigerIds[i]] = true;
}
babyTigersContract.ownerMint(msg.sender, _count);
}
// This should toggle holderSaleIsActive in the manager contract's storage
function toggleHolderSaleStatus() external onlyOwner {
holderSaleIsActive = !holderSaleIsActive;
emit HolderSaleActivation(holderSaleIsActive);
}
function toggleWhitelistSaleStatus() external onlyOwner {
babyTigersContract.toggleWhitelistSaleStatus();
}
function toggleSaleStatus() external onlyOwner {
babyTigersContract.toggleSaleStatus();
}
function setMintPrice(uint256 _mintPrice) external onlyOwner {
babyTigersContract.setMintPrice(_mintPrice);
}
function setWhitelistMintPrice(uint256 _mintPrice) external onlyOwner {
babyTigersContract.setWhitelistMintPrice(_mintPrice);
}
function setMaxPurchase(uint256 _maxPurchase) external onlyOwner {
babyTigersContract.setMaxPurchase(_maxPurchase);
}
function lockMetadata() external onlyOwner {
babyTigersContract.lockMetadata();
}
function withdraw() external onlyOwner {
babyTigersContract.withdraw();
payable(owner()).transfer(address(this).balance);
}
function setBaseURI(string memory baseURI) external onlyOwner {
babyTigersContract.setBaseURI(baseURI);
}
function setMerkleRoot(bytes32 _root) external onlyOwner {
babyTigersContract.setMerkleRoot(_root);
}
function transferBabyTigersOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "NO_ADDRESS_PROVIDED");
babyTigersContract.transferOwnership(_newOwner);
emit BabyTigersManagerChanged(_newOwner);
}
receive() external payable virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.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) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
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 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.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
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.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface InterfaceBabyTigers is IERC721 {
// Events
event SaleActivation(bool isActive);
event HolderSaleActivation(bool isActive);
event WhitelistSaleActivation(bool isActive);
// Merkle Proofs
function setMerkleRoot(bytes32 _root) external;
function isWhitelisted(
address _account,
bytes32[] calldata _proof
) external view returns (bool);
//Holder status validation
function isTypicalTigerAvailable(uint256 _tokenId) external view returns(bool);
// Minting
function ownerMint(address _to, uint256 _count) external;
function holderMint(uint256[] calldata _typicalTigerIds, uint256 _count) external;
function whitelistMint(
uint256 _count,
bytes32[] calldata _proof
) external payable;
function mint(uint256 _count) external payable;
function toggleHolderSaleStatus() external;
function toggleWhitelistSaleStatus() external;
function toggleSaleStatus() external;
function setMintPrice(uint256 _mintPrice) external;
function setWhitelistMintPrice(uint256 _mintPrice) external;
function setMaxPurchase(uint256 _maxPurchase) external;
function lockMetadata() external;
function withdraw() external;
function transferOwnership(address newOwner) external;
function getWalletOfOwner(address owner) external view returns (uint256[] memory);
function getTotalSupply() external view returns (uint256);
function setBaseURI(string memory baseURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `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}.
* ====
*/
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);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
|
Events Merkle ProofsHolder status validation Minting
|
interface InterfaceBabyTigers is IERC721 {
event SaleActivation(bool isActive);
event HolderSaleActivation(bool isActive);
event WhitelistSaleActivation(bool isActive);
function setMerkleRoot(bytes32 _root) external;
function isWhitelisted(
address _account,
bytes32[] calldata _proof
) external view returns (bool);
function isTypicalTigerAvailable(uint256 _tokenId) external view returns(bool);
function ownerMint(address _to, uint256 _count) external;
function holderMint(uint256[] calldata _typicalTigerIds, uint256 _count) external;
function whitelistMint(
uint256 _count,
bytes32[] calldata _proof
) external payable;
function mint(uint256 _count) external payable;
function toggleHolderSaleStatus() external;
function toggleWhitelistSaleStatus() external;
function toggleSaleStatus() external;
function setMintPrice(uint256 _mintPrice) external;
function setWhitelistMintPrice(uint256 _mintPrice) external;
function setMaxPurchase(uint256 _maxPurchase) external;
function lockMetadata() external;
function withdraw() external;
function transferOwnership(address newOwner) external;
function getWalletOfOwner(address owner) external view returns (uint256[] memory);
function getTotalSupply() external view returns (uint256);
function setBaseURI(string memory baseURI) external;
pragma solidity ^0.8.0;
}
| 283,471
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.